gpt4 book ai didi

entity-framework - EntityState.Deleted 正在从我的列表中删除项目

转载 作者:行者123 更新时间:2023-12-04 02:01:47 24 4
gpt4 key购买 nike

当我设置 db.Entry(episode).State = EntityState.Deleted EF 从我的列表中删除剧集并抛出 collection was modified 枚举操作可能无法执行

这是我的代码:

public async Task UpdateAsync(List<Episode> episodes)
{
using (var db = new DbContext())
{
var serie = await db.Series.Include(s => s.Episodes).SingleOrDefaultAsync(s => s.Id == id);

foreach (var episode in serie.Episodes)
{
var modifiedEpisode = episodes.Where(e => e.Id == episode.Id).SingleOrDefault();

//was deleted
if (modifiedEpisode == null)
{
db.Entry(episode).State = EntityState.Deleted;// episode is removed from serie.Episodes throwing exception
continue;
}
}

var addedEpisodes = episodes.Where(v => v.Id == Guid.Empty).ToList();
serie.Episodes.AddRange(addedEpisodes);

await db.SaveChangesAsync();
}
}

如何删除剧集?

最佳答案

正如 Shiraz Bhaiji 所说,您不能从列表中删除项目,而该列表是 foreach 语句的来源。一个简单的 ToList() 可以解决你的问题

 foreach (var episode in serie.Episodes.ToList())
{
var modifiedEpisode = episodes.Where(e => e.Id == episode.Id).SingleOrDefault();

//was deleted
if (modifiedEpisode == null)
{
db.Entry(episode).State = EntityState.Deleted;// episode is removed from serie.Episodes throwing exception
continue;
}
}

Shiraz Bhaiji 的回答也是正确的!

关于entity-framework - EntityState.Deleted 正在从我的列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30444599/

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