0

比方说,我有两个实体,例如StudentDepartment。它们之间存在一对多的关系。

学生.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; }
   }

部门.cs

 public class Department 
   {
      public int DepartmentId { get; set; }
      public int DepartmentName { get; set; }

      public ICollection<Student> Students { get; set; } 
   }

而不是使用public ICollection<Student> Students { get; set; },我可以使用

public List<Student> Students { get; set; } 

public IEnumerable<Student> Students { get; set; } 

我在 Web 的各种教程中看到了它。我应该使用哪一个??我知道我使用哪一个并不重要,但结果总是一样的。我想知道什么是最佳实践。

4

2 回答 2

2

不确定它是否是“最佳实践”,但我按照你的方式做,但也使用虚拟

   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; } 
   }

我从Scott Gu 博客中学到了这种方法。所以我希望它是好东西

于 2013-08-02T09:54:10.550 回答
0

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.

于 2013-08-03T02:48:53.717 回答