How to delete multiple rows in ASP .NET Core from a table in relation one-to-many at once?
If you want to delete the data from DB, I think the following code and references will be useful.
https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.removerange?view=efcore-5.0
How can I delete 1,000 rows with EF6?
You can edit your code this way.
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();
}
}
Since you have converted the" Location " list to ToList (), you do not need to check null. You can check with Any() method.