2010-03-02 26 views
2

我是EF 4.0的新手,所以也許這是一個簡單的問題。我有VS2010 RC和最新的EF CTP。我試圖在EF團隊的設計博客http://blogs.msdn.com/efdesign/archive/2009/10/12/code-only-further-enhancements.aspx上實施「外鍵」代碼 - 第一個示例。在Code-First和POCO中使用Entity Framework 4.0:如何獲取所有子項的父對象?

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?

回答

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; 
} 
+4

我會對這種方法持謹慎態度,因爲您正在對數據庫進行n次往返,每個客戶一次。如果你有幾個關於客戶的兒童收藏?一種更好的方法是使用Include(見下文),它將在一個查詢中將其全部檢索到數據庫。 – 2010-10-07 21:45:09

1

我與4.0/VS 2010/EF的發佈版本工作,我似乎無法找到命名空間,其中中,ContextBuilder是存儲。在CTP示例中,我已經看到它在'Microsoft.Data.Objects'中,但我似乎無法找到該引用。我在創建Model-First示例時沒有遇到任何問題,但是我陷入了我正在使用的Code-First示例中......任何幫助都非常感謝!

+5

你需要單獨下載它:http://stackoverflow.com/questions/2739808/entity-framework-contextbuilder-namespace – Chris 2010-05-21 04:37:27

3

您還可以使用:

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

或啓用惰性加載在ContextOptions:

context.ContextOptions.LazyLoadingEnabled = true; 

只是要小心延遲加載,如果你序列化對象或你可能最終查詢整個數據庫。

相關問題