使用Entity Framework 4.0与Code-First和POCO:如何获取其所有子项的父对象?

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

我是EF 4.0的新手,所以这可能是一个简单的问题。我有VS2010 RC和最新的EF CTP。我正在尝试在EF团队的设计博客上实现“外键”代码优先示例, 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>();} }
}

我使用ContextBuilder配置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);

   ...
}

这在我添加新客户时正常工作,但在我尝试检索现有客户时却无法正常工作。此代码成功保存新客户及其所有子PurchaseOrders:

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

但是这段代码只检索Customer对象;他们的PurchaseOrders列表总是空的。

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

我还需要对ContextBuilder做些什么才能使MyContext始终检索每个Customer的所有PurchaseOrders?

热门答案

你也可以使用:

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

或者在ContextOptions中启用LazyLoading:

context.ContextOptions.LazyLoadingEnabled = true;

如果要序列化对象,请注意延迟加载,否则最终可能会查询整个数据库。



许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因