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

Question

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?

1
2
3/2/2010 2:16:04 AM

Popular Answer

You could also use:

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

Or enable LazyLoading in the ContextOptions :

context.ContextOptions.LazyLoadingEnabled = true;

Just be careful with deferred loading if you are serializing the objects or you may end up querying the entire database.

3
5/25/2010 3:11:49 PM


Related Questions





Related

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