【问题标题】:The best practice to design one to many relationship in EF code first首先在 EF 代码中设计一对多关系的最佳实践
【发布时间】:2013-08-02 09:49:16
【问题描述】:

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

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

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

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

不用public ICollection&lt;Student&gt; Students { get; set; },我可以用

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

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

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

【问题讨论】:

标签: c# entity-framework ef-code-first


【解决方案1】:

不确定这是否是“最佳做法”,但我按照您的方式进行操作,但也使用 virtual

   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 blog 中学到了这种方法。所以我希望它是好东西

【讨论】:

    【解决方案2】:

    一个好的做法是:

    public virtual IList<Student> Students { get; set; }
    

    这允许您使用 IList 实现的方法并使实体框架能够在运行时创建动态代理。

    【讨论】:

      猜你喜欢
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      相关资源
      最近更新 更多