2

我是 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);

   ...
}

这在我添加新客户时可以正常工作,但在我尝试检索现有客户时却不行。此代码成功保存了一个新客户及其所有子采购订单:

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

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

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

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

4

2 回答 2

3

您还可以使用:

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

或者在 ContextOptions 中启用 LazyLoading :

context.ContextOptions.LazyLoadingEnabled = true;

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

于 2010-05-25T15:11:49.980 回答
2

好吧,正如我怀疑的那样,解决方案很简单。我为每个客户调用了 context.LoadProperty() 方法:

using (var context = _builder.Create(_conn))
{
    var customers = context.Customers.ToList();
    foreach (var customer in customers)
    {
        context.LoadProperty<Customer>(customer, c => c.PurchaseOrders);
    }
    return customers;
}
于 2010-03-04T19:11:04.930 回答