Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Lets say I've a Team class which contains 0 or more Players.

The Player class is easy:

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

But whats the best to define the 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; }
}
like image 857
Stef Heyenrath Avatar asked Apr 14 '10 10:04

Stef Heyenrath


People also ask

What is POCO model?

In software engineering, a plain old CLR object, or plain old class object (POCO) is a simple object created in the . NET Common Language Runtime (CLR) that is unencumbered by inheritance or attributes.

What is a POCO ORM?

Learn more. PetaPoco is a thin Object Relational Mapper (ORM) for . NET applications. Unlike full-fledged ORMs like NHibernate or Entity Framework, the emphasis is on simplicity of use and performance rather than richness of features.

What are the types of entities in Entity Framework?

There are two types of Entities in Entity Framework: POCO Entities and Dynamic Proxy Entities.

What is POCO classes in Entity Framework?

A Plain Old CLR Objects (POCO) is a class, which doesn't depend on any framework-specific base class. It is like any other normal . NET class. Due to this, they are called Plain Old CLR Objects.


1 Answers

First, let's dispense with the unacceptable options. Option 3 isn't really right; we are in object space, not LINQ to Entities space. Option 4 isn't right, either; ObjectSet is for use on an ObjectContext, not on a POCO type.

That leaves 1 and 2. Both of them will work correctly. The Entity Framework will initialize the collection when materializing related instances from the database if you choose not to. However, option 2 does have the advantage that you can use a new Team in your own code before saving it to the database and reading it back. So I would probably pick that one.

like image 92
Craig Stuntz Avatar answered Sep 29 '22 17:09

Craig Stuntz