2014-03-02 53 views
1

我在我的域邏輯中有一個unitOfWork,用於檢索數以萬計的XML節點,根據XML創建名爲「retreivedBooks」的斷開實體並更新數據庫中的Book實體retreivedBooks。對於我的應用程序中的這個特殊的unitOfWork的dbContext,當數據庫中有很多實體時,由於性能非常差,我禁用了更改跟蹤。這提高了性能 - 很好。實體框架沒有更新禁用自動更改跟蹤的naviation proprties

但它不再更新導航屬性。這裏是一個由例子來說明這個問題:

public class Book 
{ 
     public string Title; 
     public string Author; 
     public virtual List<Page> Pages; 
} 

_unitOfWork.Context.Configuration.AutoDetectChangesEnabled = false; 
_unitOfWork.Context.Configuration.ValidateOnSaveEnabled = false; 

foreach(Book retreivedBook in retreivedBooks) 
{ 
    Book existingBook= _unitOfWork.BookRepository.SingleOrDefault(b=>b.Id=retreivedBook.Id); 
    if(book!=null) 
    { 
     existingBook.Title=retreivedBook.Title; 
     existingBook.Author=retreivedBook.Author; 
     existingBook.Pages=retreivedBook.Pages; 
     _unitOfWork.Context.Entry(existingBook).State = EntityState.Modified; 
    } 
} 
_unitOfWork.Save(); 

在上面的例子中,標題和數據庫中的圖書作者的屬性得到正確更新,但頁面的列表不。

順便說一句,我不檢查基於retreived頁面的現有頁面。我們可以假設頁面每次都是不同的,所以book.Pages屬性將在每次更新時被替換。

任何人都可以幫助解釋爲什麼頁面屬性不會更新數據庫中?

回答

0

由於Entity Framework的工作方式,當您設置_unitOfWork.Context.Configuration.AutoDetectChangesEnabled = false;很可能不會更新子實體。爲了解決這個問題,在保存更改之前應該將狀態更改爲true。換句話說試試這個在您的代碼:

... 
_unitOfWork.Context.Entry(existingBook).State = EntityState.Modified; 
    } 
} 
_unitOfWork.Context.Configuration.AutoDetectChangesEnabled = true; 
_unitOfWork.Save(); 
+0

是的,這將修復它,但提到當AutoDetectChanges是,當有大量的實體在數據庫中,因爲它有加載整個對象圖enabledI獲得性能極差每當EF調用DetectChanges(或其他) –

+0

@DanCook那麼,它只是爲了能夠更新子實體。我很肯定你可以'_unitOfWork.Context.Configuration.AutoDetectChangesEnabled = true; _unitOfWork.Save(); _unitOfWork.Context.Configuration.AutoDetectChangesEnabled = false;' 或其他一些解決方法。 – Leron