2

Can someone help me understand what purpose the Department constructor has in the class below, taken from 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; } 
} 

Versus this example where they don't use a constructor, taken from 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; }
   }

The Course class is identical in both.

Is this just a case of the latter being EF6 and the former deprecated?

Thanks

2
  • Are you asking about the initialization of the Courses property? Commented Mar 18, 2015 at 18:30
  • Correct, I see two different tutorials for essentially the same example. One has the initialization, and one doesn't. Would like to understand the purpose of it, and if thats required in EF6 because its not present in the EF6 tutorial. public Department() { this.Courses = new HashSet<Course>(); } Commented Mar 18, 2015 at 18:35

1 Answer 1

2

It just lets Courses always be initialized.

Imagine this:

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

In the first example you gave, the one with the constructor, it's fine. For the second example, this will throw a NullReferenceException as the Courses object hasn't been initialized.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.