Using Entity Framework 4.0 with Code-First and POCO: How to Get Parent Object with All its Children

Posted by SirEel on Stack Overflow See other posts from Stack Overflow or by SirEel
Published on 2010-03-02T02:16:04Z Indexed on 2010/05/01 14:07 UTC
Read the original article Hit count: 198

I'm new to EF 4.0, so maybe this is an easy question. I've got VS2010 RC and the latest EF CTP. I'm trying to implement the "Foreign Keys" code-first example on the EF Team's Design Blog, http://blogs.msdn.com/efdesign/archive/2009/10/12/code-only-further-enhancements.aspx.

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 use a ContextBuilder to configure MyContext:

{
   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);

   ...
}

This works correctly when I'm adding new Customers, but not when I try to retrieve existing Customers. This code successfully saves a new Customer and all its child PurchaseOrders:

using (var context = builder.Create(connection))
{
   context.Customers.AddObject(customer);
   context.SaveChanges();
}

But this code only retrieves Customer objects; their PurchaseOrders lists are always empty.

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

What else do I need to do to the ContextBuilder to make MyContext always retrieve all the PurchaseOrders with each Customer?

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about code-first