有人可以帮我理解下面类中 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/