实体框架 - Code First 使用自定义构造函数实现多对多关系
据我研究使用 Code First 定义多对多关系,我猜想实体类中的自定义构造函数仅用于创建实体的新实例以及 n:m 相关实体的目的立刻。
目前,我的类定义如下:
public class Person
{
public Person()
{
Events = new HashSet<Event>();
}
public int PersonId { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class Event
{
public Event()
{
Persons = new HashSet<Person>();
}
public int EventId { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
但是,如果我的应用程序永远不会提供在创建新事件期间创建新人员的可能性,我可以简单地省略事件的自定义构造函数吗?
public class Event
{
public int EventId { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
多对多关系还能正常工作吗?
As far as I did research on defining many to many relations with Code First, I guess that custom constructors in the entity classes are only needed for the purpose of being able to create a new instance of an entity plus the n:m-related entity AT ONCE.
At the moment I have my classes defined like this:
public class Person
{
public Person()
{
Events = new HashSet<Event>();
}
public int PersonId { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class Event
{
public Event()
{
Persons = new HashSet<Person>();
}
public int EventId { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
However, if my application will never offer the possibility to create a new Person during creating a new Event, can I simply omit the custom constructor for Events?
public class Event
{
public int EventId { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
Will the many to many relation still work fine?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果这样做,当您创建新事件并尝试向其中添加人员时,您将收到 NullReferenceException。
这是该构造函数初始化集合的唯一原因。
您可以在第一次访问时在 getter 内延迟初始化 Persons 集合,但需要小心多线程。
If you do that you'll get a NullReferenceException when you create a new event and try to add Persons to it.
that is the only reason for that constructor, to initialise the collections.
you can initialise the Persons collection lazily inside the getter on first access but you need to be careful with multithreading.