0

Let say, I have two entites such as Student and Department. There is one to many relationship between them.

Student.cs

public class Student 
   {
      public int StudentId { get; set; }
      public int StudentName { get; set; }
      public int StudentRoll { get; set; }

      public int DepartmentId { get; set; }
      public Department Department { get; set; }
   }

Department.cs

 public class Department 
   {
      public int DepartmentId { get; set; }
      public int DepartmentName { get; set; }

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

Instead of using public ICollection<Student> Students { get; set; }, I can use

public List<Student> Students { get; set; } 

public IEnumerable<Student> Students { get; set; } 

I saw it in various tutorial in Web. Which one should I use?? I know that it doesn't matter which one I am using but the result is always same. I want to know what is the best practice.

Atish Dipongkor
  • 9,380
  • 8
  • 45
  • 75
  • 2
    More important is the `virtual` keyword. Here's a [good answer (for 4.1)](http://stackoverflow.com/a/5599270/60761) – Henk Holterman Aug 02 '13 at 09:52
  • ICollection is default implementations for Navigation Property. The virtual keyword is not necessary needed if you don't need lazy loading. – Harris Yer Aug 02 '13 at 10:02
  • Some additional links about Collections/Lists/etc: http://stackoverflow.com/questions/376708/ilist-vs-ienumerable-for-collections-on-entities, http://stackoverflow.com/questions/271710/collectiont-versus-listt-what-should-you-use-on-your-interfaces, http://stackoverflow.com/questions/3628425/ienumerable-vs-list-what-to-use-how-do-they-work, http://stackoverflow.com/questions/398903/what-is-the-difference-between-list-of-t-and-collectionof-t – Chris Aug 02 '13 at 10:03

2 Answers2

2

Not sure if its the "best practice", but I do it the way you've done it, but use virtual as well.

   public class Student 
   {
      public int StudentId { get; set; }
      public int StudentName { get; set; }
      public int StudentRoll { get; set; }

      public int DepartmentId { get; set; }
      public virtual Department Department { get; set; }
   }

   public class Department 
   {
      public int DepartmentId { get; set; }
      public int DepartmentName { get; set; }

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

I picked up this approach from Scott Gu blog . so I hope its good stuff

owen79
  • 1,428
  • 1
  • 16
  • 33
0

A good practice is:

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

This allow you to use the methods implemented by IList and enable Entity Framework to create dynamic proxies at runtime.