[英]The best practice to design one to many relationship in EF code first
Let say, I have two entites such as Student and Department . 比方说,我有两个参与者,如学生和部门 。 There is one to many relationship between them. 他们之间有一对多的关系。
Student.cs Student.cs
public class Student
{
public int StudentId { get; set; }
public int StudentName { get; set; }
public int StudentRoll { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
Department.cs Department.cs
public class Department
{
public int DepartmentId { get; set; }
public int DepartmentName { get; set; }
public ICollection<Student> Students { get; set; }
}
Instead of using public ICollection<Student> Students { get; set; }
而不是使用public ICollection<Student> Students { get; set; }
public ICollection<Student> Students { get; set; }
public ICollection<Student> Students { get; set; }
, I can use public ICollection<Student> Students { get; set; }
,我可以使用
public List<Student> Students { get; set; }
public IEnumerable<Student> Students { get; set; }
I saw it in various tutorial in Web. 我在Web的各种教程中看到了它。 Which one should I use?? 我应该使用哪一个? I know that it doesn't matter which one I am using but the result is always same. 我知道我使用哪一个并不重要,但结果总是一样的。 I want to know what is the best practice. 我想知道什么是最佳做法。
Not sure if its the "best practice", but I do it the way you've done it, but use virtual as well. 不确定它是否是“最佳实践”,但我按照你的方式做到了,但也使用虚拟 。
public class Student
{
public int StudentId { get; set; }
public int StudentName { get; set; }
public int StudentRoll { get; set; }
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public int DepartmentName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
I picked up this approach from Scott Gu blog . 我从Scott Gu博客那里学到了这种方法。 so I hope its good stuff 所以我希望它的好东西
A good practice is: 一个好的做法是:
public virtual IList<Student> Students { get; set; }
This allow you to use the methods implemented by IList and enable Entity Framework to create dynamic proxies at runtime. 这允许您使用IList实现的方法,并使Entity Framework能够在运行时创建动态代理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.