C# EntityFramework delete all rows from a database table that correspond to specific value?

Viewed 30

Is there an efficent way of deleting all rows from a database matching a specified criteria?

Say i have a table that has three columns:

  • MyTableId --> PrimaryKey
  • PeopleId --> ForeignKey
  • ActivityGroupId --> ForeignKey

How do i delete all records from table containing a specific PeopleId using Ef Core?


I could do this:

 var MyTable = await context.MyTable //checking if the criteria exists in the table before deleting
     .FirstOrDefaultAsync(x => x.PeopleId == peopleId); // here peopleId is my criteria

 if (MyTable != null) {
     var list = context.MyTableSelect(x => x.MyTableId).Where(x => x.PeopleId == peopleId).ToList();
     foreach (var idToRemove in list) {
     context.MyTable.Remove();
     }
     await context.SaveChangesAsync();
    }

But wouldn't that foreach be a 'bad practice' i think there is a better way to do that... any suggestions?

0 Answers
Related