2

I want to know the difference between those two codes can't understand what should I initialize the property in the constructor: Code 1:

public class Student
{
    public Student() 
    {
        this.Courses = new HashSet<Course>();
    }

    public int StudentId { get; set; }
    [Required]
    public string StudentName { get; set; }

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

public class Course
{
    public Course()
    {
        this.Students = new HashSet<Student>();
    }

    public int CourseId { get; set; }
    public string CourseName { get; set; }

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

code2:

public class Student
{  
    public int StudentId { get; set; }
    [Required]
    public string StudentName { get; set; }

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

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }

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

can anyone help me to understand the meaning of the difference for those two codes , thanks

Zaker typoir
  • 99
  • 1
  • 2
  • 8
  • Possible duplicate of [using hashset in entity framework](http://stackoverflow.com/questions/11131617/using-hashset-in-entity-framework) – Usman May 11 '17 at 22:42
  • 1
    Initializing the property in the constructor is useful if you want to avoid getting null-reference exceptions when using your object outside the EF data context. @Usman The accepted answer in that question is not really relevant to what this question is asking. – Asad Saeeduddin May 11 '17 at 22:47

1 Answers1

2

Avoiding null reference exception while using the model in DB context, or Generally speaking, it is best to use the collection that best expresses your intentions. If you do not specifically intend to use the HashSet's unique characteristics, I would not use it.

AlameerAshraf
  • 872
  • 1
  • 13
  • 23