I am trying to delete several records from the Locations
table at once. However, I get an exception after the second pass of the foreach loop. There is also a RemoveRange
method, but it takes index
and count
, but in this case, I don't have these parameters to use this method. How can I in this case remove several items at once from a table that is in relation one-to-many?
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();
}
}