2012-11-26 62 views
0

實體可以找到對象並可以設置它的屬性,但它會拋出「該對象無法刪除,因爲它在ObjectStateManager中找不到」。當我嘗試刪除它時例外。 你可以看到我的故事屬於圖片。如你所見,對象不是null,實體可以找到它。實體可以找到對象但它不能刪除它

enter image description here

我可以看到whicgh我想在上下文中刪除的對象。

enter image description here

你對此有什麼建議嗎?

感謝,

+0

你是如何從數據庫中檢索實體?看起來該實體沒有被追蹤。你使用'AsNoTracking()'方法嗎? –

+0

我使用以下代碼檢索:using(var context = new eTicaretEntity()) { return context.carts.FirstOrDefault(x => x.CartGuid == cartGuid && x.ProductId == productId && x.ProductTypeId == productTypeId); } – cagin

+0

您需要使用相同的上下文來刪除實體,以便上下文可以跟蹤它。嘗試將代碼刪除使用語句中的實體 –

回答

0

的問題是,你所得到的實體後處置權的背景下。通過這種方式,實體框架無法追蹤對該實體發生的變化。 嘗試把刪除代碼的使用語句中:

using (var context = new eTicaretEntity()) 
{ 
    var cart = context.carts.FirstOrDefault(x => 
     x.CartGuid == cartGuid && 
     x.ProductId == productId 
     && x.ProductTypeId == productTypeId); 

    // delete entity here 
    // ..... 
} 
+0

是的,它現在有效。謝謝.. – cagin

+0

不客氣:) –

相關問題