entity-framework - Entity Framework 模型类中构造函数的用法

标签 entity-framework

有人可以帮我理解下面类中 Department 构造函数的用途吗,摘自 https://msdn.microsoft.com/en-us/data/jj591617.aspx

public class Department 
{ 
    public Department() 
    { 
        this.Courses = new HashSet<Course>(); 
    } 
    // Primary key 
    public int DepartmentID { get; set; } 
    public string Name { get; set; } 
    public decimal Budget { get; set; } 
    public System.DateTime StartDate { get; set; } 
    public int? Administrator { get; set; } 

    // Navigation property 
    public virtual ICollection<Course> Courses { get; private set; } 
} 

与此示例相比,他们不使用构造函数,取自 http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

 public class Department
   {
      public int DepartmentID { get; set; }

      [StringLength(50, MinimumLength=3)]
      public string Name { get; set; }

      [DataType(DataType.Currency)]
      [Column(TypeName = "money")]
      public decimal Budget { get; set; }

      [DataType(DataType.Date)]
      [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
      [Display(Name = "Start Date")]
      public DateTime StartDate { get; set; }

      public int? InstructorID { get; set; }

      public virtual Instructor Administrator { get; set; }
      public virtual ICollection<Course> Courses { get; set; }
   }

两者的 Course 类是相同的。

这只是后者是 EF6 而前者已弃用的情况吗?

谢谢

最佳答案

它只是让类(class)始终被初始化。

想象一下:

var d = new Department();
d.Courses.Add(new Course());

在您给出的第一个示例中,带有构造函数的示例,没问题。对于第二个示例,这将引发 NullReferenceException,因为 Courses 对象尚未初始化。

关于entity-framework - Entity Framework 模型类中构造函数的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29129851/

相关文章:

c# - 复杂类型引用的 EagerLoad 实体

c# - 仅使用一个 dbContext 对多个数据库执行投影

c# - 数据库实体的 MVC 错误

c# Entity Framework sqlite (spatialite) 空间日期

entity-framework - Entity Framework -使用toTraceString查看Sql

asp.net-mvc - 使用来自 2 个不同数据库的表 - Entity Framework

c# - 鉴于我们只想要第一条记录,在 linq 查询中选择之前排序是否更好?

c# - .NET Entity Framework 插入与批量插入

C# webapi 异步上下文问题

c# - 首先使用实体​​框架代码获取外键值