2012-02-27 43 views
0

我一直試圖找出一個很好的解決方案,大部分的下午,但無濟於事。從分離狀態刪除關係

當我使用實體框架(EF)查詢數據時,我總是使用MergeOption.NoTracking,因爲我不想在我的視圖中使用數據庫對象進行顯示。我最終將EF生成的POCO類映射到視圖模型中,這些視圖模型具有可愛的小屬性,如必需的,顯示名稱等。當我需要進行更新時,我最終將我的視圖模型映射回生成的類通過實體框架並執行創建或更新操作。

我試圖找到一種簡單的方法來刪除與我的對象的關係,但由於它們是分離的,我一直沒能找到辦法做到這一點。我看到有人推薦附加和刪除對象,但由於我的對象被分離了,所以不起作用(它導致信息Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached.的異常)。

這裏是我當前的代碼示例:

//Find the records that need to be deleted. 
    var productVersionsToDelete = (from pv in existingDownloadFile.ProductVersions 
            where !selectedVersions.Contains(pv.Id) 
            select pv).ToList(); 

    foreach (var productVersionToDelete in productVersionsToDelete) { 
     existingDownloadFile.ProductVersions.Attach(productVersionToDelete); 
     existingDownloadFile.ProductVersions.Remove(productVersionToDelete); 
    } 

沒有人有從分離狀態刪除對象的建議?

回答

1

問題是,一旦調用attach,整個對象圖就會被附加。給定一個DbContext稱爲context,這應該工作將是以下的例子:

// Attach the download file to the context set (this will attach all ProductVersions 
context.DownloadFiles.Attach(existingDownloadFile); 

//Find the records that need to be deleted. 
var productVersionsToDelete = (from pv in existingDownloadFile.ProductVersions 
           where !selectedVersions.Contains(pv.Id) 
           select pv).ToList(); 

foreach (var productVersionToDelete in productVersionsToDelete) 
    existingDownloadFile.ProductVersions.Remove(productVersionToDelete); 

context.SaveChanges(); 

這是假定DownloadFiles是屬性的名字寫在你DbContext暴露匹配的existingDownloadFile類型哪些實體。

你得到的例外是因爲一旦你附加ProductVersion,它附加相關的existingDownloadFile,它只能附加一次。

+0

謝謝你的幫助,那就是訣竅。一個問題,但。我的情況下'existingDownloadFile'沒有附加。我的所有物品都處於分離狀態。發生錯誤是因爲關係鏈中的頂級對象需要連接嗎?我仍然不確定自己是否裹過腦袋,爲什麼會發生錯誤。 – 2012-02-28 00:18:30

+0

我相信當你附加第一個'productVersionToDelete'時,它有一個引用回到'existingDownloadFile',這會導致它被連接。下一次調用attach時,它試圖再次附加'existingDownloadFile',但它第一次連接,所以發生錯誤。 – Lukazoid 2012-02-28 00:20:11