How to Get Parent Object with All Its Children in Entity Framework 4.0 using Code-First and POCO?

code-first entity-framework one-to-many poco


EF 4.0 is new to me, so maybe this is a simple inquiry. I have the most recent EF CTP as well as VS2010 RC. On the EF Team's Design Blog,, I'm attempting to put the "Foreign Keys" code-first example into practice.

public class Customer
   public int Id { get; set; 
   public string CustomerDescription { get; set; 
   public IList<PurchaseOrder> PurchaseOrders { get; set; }

public class PurchaseOrder
   public int Id { get; set; }
   public int CustomerId { get; set; }
   public Customer Customer { get; set; }
   public DateTime DateReceived { get; set; }

public class MyContext : ObjectContext
   public RepositoryContext(EntityConnection connection) : base(connection){}
   public IObjectSet<Customer> Customers { get {return base.CreateObjectSet<Customer>();} }

I set up MyContext using a ContextBuilder:

   var builder = new ContextBuilder<MyContext>();

   var customerConfig = _builder.Entity<Customer>();
   customerConfig.Property(c => c.Id).IsIdentity();

   var poConfig = _builder.Entity<PurchaseOrder>();
   poConfig.Property(po => po.Id).IsIdentity();

   poConfig.Relationship(po => po.Customer)
      .FromProperty(c => c.PurchaseOrders)
      .HasConstraint((po, c) => po.CustomerId == c.Id);


When I attempt to retrieve existing Customers, it doesn't operate properly; it only works when I add new customers. A new Customer and all of its child PurchaseOrders are correctly saved using this code:

using (var context = builder.Create(connection))

However, the PurchaseOrders lists returned by this function are never empty; they only return Customer objects.

   using (var context = _builder.Create(_conn))
      var customers = context.Customers.ToList();

What further changes must I make to the ContextBuilder to ensure that MyContext always retrieves every PurchaseOrder associated with every Customer?

3/2/2010 2:16:04 AM

Popular Answer

Additionally, use:

var customers = context.Customers.Include("PurchaseOrders").ToList();

Alternatively, enable LazyLoading in ContextOptions:

context.ContextOptions.LazyLoadingEnabled = true;

If you are serializing the objects, just be cautious while using delayed loading since you don't want to end up searching the whole database.

5/25/2010 3:11:49 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow