首页 > 解决方案 > 如何一次从一对多关系的表中删除 ASP .NET Core 中的多行?

问题描述

我正在尝试Locations一次从表中删除几条记录。但是,在 foreach 循环的第二次通过后出现异常。还有一个RemoveRange方法,但是它需要indexand 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();
   }
}

删除范围

标签: c#entity-frameworkasp.net-core.net-coreentity-framework-core

解决方案


如果你想从数据库中删除数据,我认为下面的代码和参考资料会很有用。

https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.removerange?view=efcore-5.0

如何使用 EF6 删除 1,000 行?

您可以通过这种方式编辑您的代码。

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() 方法进行检查。


推荐阅读