2013-05-14 18 views
1

我在使用POCO的實體框架中遇到了一些問題,我希望有人可以在高層告訴我,如果我看到的行爲是預期的或者我需要深入研究它爲什麼會發生。禁用代理創建和延遲加載的實體框架仍在加載子對象

我有一個類Customer和另一CustomerType,所以Customer具有(指示型的CustomerType類型)的Type財產和CustomerType具有財產Customers這是Customer S(所有Customer S作這種類型的),所以這些集合基本上上的關聯的兩端的導航屬性,導致POCO碼是這樣的:

public partial class Customer 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int TypeId { get; set; } 
    public CustomerType Type { get; set; } 
} 

public partial class CustomerType 
{ 
    public CustomerType() 
    { 
     this.Customers = new HashSet<CustomerType>(); 
    } 

    public int Id { get; set; } 
    public string TypeName { get; set; } 

    public virtual ICollection<Customer> Customers { get; set; } 
} 

我已經關閉代理創建和惰性加載(即兩個DbContext.Configuration.ProxyCreationEnabled=falseDbContext.Configuration.LazyLoadingEnabled=false),因爲它們使序列化變得很痛苦。

正如預期的那樣,當我從Customer集合中獲取實例時,默認情況下它們的Type屬性爲null。

但是,如果我從Customer實例集合了.Include("Type"),它不僅是加載Type性能,但它也裝載了兒童 - 即Customer S於每一種集合。

這是預期嗎?

+1

我不知道你的意思是「MyClass」和「MyClassType」。也許你可以爲這兩個類編寫C#代碼,而不是試圖描述它。 – Aron 2013-05-14 02:52:59

+0

對不起,命名很混亂 - 我的編輯更清楚了嗎?這些只是試圖說明這個概念的例子。 – mutex 2013-05-14 04:15:10

+0

不...沒有幫助。 [看看這裏的例子,你應該如何描述你的類](http://stackoverflow.com/questions/16523686/unable-to-determine-the-principal-end-of-an-association)。我們是這裏的開發者,而不是英語專業。我們發現代碼比散文容易閱讀。 – Aron 2013-05-14 04:19:24

回答

2

這是半預期的。包含擴展會影響運行的SQL。那些根據CustomerType.ParentId列加載的CustomerType(通過包含在Customer查詢中)將被構建到對象樹中。

因此,如果通過一些偶然事件,父母和孩子都被加載到相同的查詢中,則該孩子將被塞進父母。

+0

謝謝,是的,我確認了一個測試項目。這對序列化非常惱人,但我想解決方案是刪除CustomerType上自動創建的Customers屬性。 PS:我在我的類定義中有一個小錯誤,所以你的答案可能應該是:「根據Customer.TypeId列將被加載的那些客戶構建到對象樹中」 – mutex 2013-05-14 20:56:29