How to define a collection in POCO in Entity Framework 4?

Suppose I have a Team class that contains 0 or more Players .

The Player class is simple:

public class Player { public long Id { get; set; } public string Name { get; set; } public Team Team { get; set; } } 

But what is the best way to define a Team class?

Option 1

 public class Team { public long Id { get; set; } public string Name { get; set; } public ICollection<Player> Players { get; set; } } 

Option 2:

 public class Team { public Team() { Players = new Collection<Player>(); } public long Id { get; set; } public string Name { get; set; } public ICollection<Player> Players { get; set; } } 

Option 3:

 public class Team { public long Id { get; set; } public string Name { get; set; } public IQueryable<Player> Players { get; set; } } 

Option 4:

 public class Team { public long Id { get; set; } public string Name { get; set; } public ObjectSet<Player> Players { get; set; } } 
+6
collections entity-framework iqueryable poco
source share
1 answer

First, let’s reject the unacceptable options. Option 3 is not quite right; we are in the space of objects, not in the space of LINQ to Entities. Option 4 is not suitable; ObjectSet used for an ObjectContext , not for a POCO type.

This leaves 1 and 2. Both will work correctly. Entity Framework will initialize the collection when you materialize the corresponding instances from the database, if you do not. However, option 2 has the advantage that you can use the new Team in your own code before storing it in the database and reading it. So I would choose this one.

+7
source share

All Articles