簡體   English   中英

刪除相關實體時“收集已修改”錯誤

[英]'Collection was modified' error when Deleting Related Entities

我試圖使用Entity Framework刪除一些項目。 我想刪除那些不在int[] destinationIds DestinationId項目。 (我正在刪除聯結表中的行。)

foreach (var destination in product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)))
    product.ImportedProductDestinations.Remove(destination);

但是foreach語句給出了運行時錯誤:

收集被修改; 枚舉操作可能無法執行。

好吧,我想我理解這個錯誤。 但我怎么能做我想做的事呢?

不要從正在掃描的集合中刪除該項目,將其從db上下文中刪除

context.IMportedProductDestinations.DeleteObject(destination);

然后使用context.SaveChanges將更改應用於db

您將獲得異常,因為您正在嘗試使用foreach迭代集合並從中刪除項目。 您可以將ToList添加到您的product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId))然后刪除該項目。

foreach (var destination in product.ImportedProductDestinations
                                   .Where(ipd => !destinationIds.Contains(ipd.DestinationId))
                                   .ToList())
{
    product.ImportedProductDestinations.Remove(destination);
}

當你在foreach中迭代它時,你不能從集合中刪除一個項目。

var result = product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)).ToList());

    For(int i= 0;i<result.count();i++)
    (
       product.ImportedProductDestinations.Remove(result[i]);
    )

創建刪除列表:

 foreach (var destination in product.ImportedProductDestinations.Where(ipd => !destinationIds.Contains(ipd.DestinationId)))
     ListRemove.Add(ipd.DestinationId)

foreach (var remove in  ListRemove)
product.ImportedProductDestinations.Remove(remove)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM