有人可以帮我理解部门构造函数在下面的课程中的用途,取自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; }
}
两个课程课程相同。
这只是后者的情况是EF6而前者被弃用了吗?
由于
答案 0 :(得分:1)
它只是让Courses
始终被初始化。
想象一下:
var d = new Department();
d.Courses.Add(new Course());
在你提供的第一个例子中,带有构造函数的那个例子很好。对于第二个示例,这将抛出NullReferenceException
,因为Courses对象尚未初始化。