2011-03-22 42 views
6

我有兩個簡單的類首先由代碼生成。實體框架 - 代碼優先不加載引用的對象

public class Company 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual Address Address { get; set; } 
} 

public class Address 
{ 
    public int Id { get; set; } 
    public string Country { get; set; } 
    ... 
} 

在數據庫中保存公司後,我有公司(ID = 1 |名= 「嗒嗒」 | AddressId = 1)和它的地址(ID = 1,國家= 「波蘭」)。當我試圖從我的DbContext加載:

Company company = context.Companies.Find(id); 

我得到公司與空地址屬性。我究竟做錯了什麼?

(我使用CTP5)

+0

順便說一句。不使用CTP5已經有EF 4.1 RC,它有API的「最終」版本:http://www.microsoft.com/downloads/en/details.aspx?FamilyID=2dc5ddac-5a96-48b2-878d-b9f49d87569a – 2011-03-22 08:48:11

+0

你是如何訪問「地址」的。應該有延遲加載觸發。 – 2011-03-22 08:49:43

+0

我檢查了我的版本。我有EntityFramework.dll運行版本v4.0.30319和版本4.0.0.0。當我使用nuget時,我得到' PM> Install-Package EntityFramework 'EntityFramework 4.1.10311.0'已經安裝。 I-mo已經有了'EntityFramework 4.1.10311.0'的引用。'' 這是奇怪的,懶惰的負載仍然無法正常工作。 – bizon 2011-03-22 09:44:46

回答

5

試試這個:

Company company = context.Companies.Include("Address").Find(id); 

或新類型化的語法:

Company company = context.Companies.Include(c => c.Address).Find(id); 

這告訴EF熱切加載Address實體你的Company實體的一部分。

它似乎還有EF上的存儲庫層 - 確保您的存儲庫實現支持Include()如果是這種情況。

只是個開始這是Include()朱莉婭·勒曼提供了「編程實體框架」支持單位可測試庫模式與POCOS(此版本只適用於第一種語法)實現:

public static IQueryable<TSource> Include<TSource>(this IQueryable<TSource> source, string path) 
{ 
    var objectQuery = source as ObjectQuery<TSource>; 
    if (objectQuery != null) 
    { 
     return objectQuery.Include(path); 
    } 
    return source; 
} 
+1

或者你可以使用更通用的自定義擴展包括:http://stackoverflow.com/questions/5376421/ef-including-other-entities-generic-repository-pattern/5376637#5376637 – 2011-03-22 08:50:28