我是 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?