![](/img/trans.png)
[英]“Collection was modified; enumeration operation may not execute” error when deleting
[英]'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.