gpt4 book ai didi

c# - 删除相关实体时出现“集合已修改”错误

转载 作者:行者123 更新时间:2023-11-30 19:26:16 26 4
gpt4 key购买 nike

我正在尝试使用 Entity Framework 删除一些项目。我想删除那些 DestinationId 不在 int[] destinationIds 中的项目。 (我正在删除联结表中的行。)

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

但是 foreach 语句给了我运行时错误:

Collection was modified; enumeration operation may not execute.

好的,我想我理解了这个错误。但是我还能如何做我想做的事情呢?

最佳答案

不要从您正在扫描的集合中删除项目,将其从数据库上下文中删除

context.IMportedProductDestinations.DeleteObject(destination);

然后使用 context.SaveChanges 将更改应用到数据库

关于c# - 删除相关实体时出现“集合已修改”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com