2013-06-27 86 views
5

我一直在尋找一段時間,沒有什麼我可以找到的作品。我有一種情況,我有兩個對象(請參見下面的定義)。子對象是父對象的集合。我在Visual Studio 2012的工作與WPF /棱鏡和Entity Framework 4.4實體框架4.4,重新加載子集合對象

class Parent 
{ 
    ...other properties... 
    public virtual ICollection<Child> Children { get; set; } 
} 

class Child 
{ 
    public string Value1 { get; set } 
    public string Value2 { get; set } 
    public string Value3 { get; set } 
} 

我有了父裝載到在左側列表框,並在項目中的一個用戶單擊窗體該列表,我們在右側顯示屬性。一切正常,直到我們有兩臺機器碰到同一個數據庫。如果一臺機器添加或更新其中一個記錄,我遇到了第二臺機器獲取數據的問題...

我有以下代碼嘗試修復它,但它似乎應該有一個簡單的方法在實體框架內。

DbEntityEntry<Parent> entry = dbContext.Entry(parent); 
entry.Reload(); //Note: this refreshes the properties on the Parent object (but not the collection 

if (Parent.Children != null) 
{ 
    Array a = doc.Children.ToArray<Child>(); //this is here because they may have deleted one of the records 

    foreach (Child g in a) 
    { 
     DbEntityEntry<Child> c= dbContext.Entry(g); 
     c.Reload(); //Note: if it is deleted, the Parent.Child gets updated automatically to remove the record. 
    } 
} 

entry.Collection(o => o.Children).Load(); //call this to get new records 

什麼我可以做的更好或者這是做它的方式有什麼想法我?????

+0

+1,因爲我覺得它是一個很好的解決方案(我知道'重新加載'從子集合中刪除已刪除的實體)。我懷疑你可以把它壓縮成一個簡單的一行代碼。使用EF更新/刷新對象圖很少容易。 – Slauma

+0

我的解決方案中存在的一個問題是,在我的實際代碼中,我有這些類型的集合中的4-5個。看起來像第一次重新加載也應該重新加載所有的子集合,或者至少是ntry.Collection(o => o.Children).Load();也許應該有一個 「刷新」,而不是 – adondero

+1

找到一個更好的方式做的foreach上述陣列上 '((IObjectContextAdapter)的DbContext).ObjectContext.Refresh(RefreshMode.StoreWins,parent.Children);' 這個條目中刪除並更新當前的。仍然需要.Load()來獲取新記錄。這似乎也快很多。 – adondero

回答

12

提出這一個答案

找到一個更好的辦法做了「的foreach」上述陣列

((IObjectContextAdapter)dbContext).ObjectContext.Refresh(RefreshMode.StoreWins, parent.Children); 

這個刪除條目,並更新現有的人上。仍然需要.Load()來獲取新記錄。這似乎也快很多