c# - 如何一次从一对多关系的表中删除 ASP .NET Core 中的多行?
问题描述
我正在尝试Locations
一次从表中删除几条记录。但是,在 foreach 循环的第二次通过后出现异常。还有一个RemoveRange
方法,但是它需要index
and count
,但是在这种情况下,我没有这些参数来使用这个方法。在这种情况下,如何从一对多关系的表中一次删除多个项目?
public async Task RemoveMultipleLocations(int id, IEnumerable<int> locationsIds)
{
var profile = await context.AlertProfiles.Include(x => x.Locations).FirstOrDefaultAsync(x => x.Id == id);
var existing = profile.Locations.Where(x => locationsIds.Contains(x.Id)).ToList();
if(existing != null)
{
foreach(var ex in existing)
{
profile.Locations.Remove(ex);
}
profile.ModifiedDate = DateTimeOffset.Now;
await context.SaveChangesAsync();
}
}
解决方案
如果你想从数据库中删除数据,我认为下面的代码和参考资料会很有用。
您可以通过这种方式编辑您的代码。
public async Task RemoveMultipleLocations(int id, IEnumerable<int> locationsIds)
{
var profile = await context.AlertProfiles.Include(x => x.Locations).FirstOrDefaultAsync(x => x.Id == id);
var existing = profile.Locations.Where(x => locationsIds.Contains(x.Id)).ToList();
if(existing.Any())
{
context.Locations.RemoveRange(existing);
await context.SaveChangesAsync();
}
}
由于您已将“Location”列表转换为 ToList(),因此无需检查 null。您可以使用 Any() 方法进行检查。
推荐阅读
- javascript - bootboxjs 无效提示类型 - 文档中的示例不起作用
- python - Import Error: Symbol not found: _PQencryptPasswordConn 是什么意思,我该如何解决?
- javascript - 在使用地理编码器时添加多个标记以响应谷歌地图
- java - 如何停止复选框与其文本对齐
- google-apps-script - 有没有办法使用 Apps Script 将文本替换为 Google Docs 中的建议?
- django - 如何使用 startproject --template?(Django 2.2)
- shell - 将 CSV 转换为文本文件的 Shell 脚本
- sql - ORA-04091“更新后”触发器出错,如何解决?
- html - 使用 CSS 制作动画图片库的最佳实践
- ios - buildMenu 在 AppDelegate 中被调用,而不是 UIViewController