Wednesday, October 14, 2009

POCO in Entity Framework 4.0

The new version (4.0) of Entity Framework allows us to use “Plain Old CLR Objects” as entities. In the current version (3.5) every entity must inherit from EntityObject, but in the new version it is possible to use a simple POCO:

public class Order
  public Guid Id { get; set; }
  public Product Product { get; set; }
  public int Quantity { get; set; } 

In order to use this new feature it is necessary to follow these three steps:
1. Create the edmx file (ModelEntities). 
2. Turn off the code generation removing the value of the “Custom Tool” property.
3. Create the context this way:

public class ModelContext : ObjectContext
  public ModelContext() : base("name=ModelEntities", "ModelEntities")  

  public ObjectSet<Order> Orders
    get { return base.CreateObjectSet<Order>(); }

More information:
POCO in the Entity Framework: Part 1 - The Experience
POCO in the Entity Framework: Part 2 – Complex Types, Deferred Loading and Explicit Loading
POCO in the Entity Framework: Part 3 – Change Tracking with POCO

No comments: