1

I am trying to delete multiple rows as such. The following code does the trick but kind of worries as the ForEach seems to indicate it may delete more than what the Where clause has. Is there a better way to do this or is the coding below sound?

db.task_Commt.Where(u => u.GlobalId == companyId
    && u.ItemId == itemId).ToList().ForEach(db.task_task_Commt.DeleteObject);
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

2 Answers2

1

Use the RemoveRange() function of EF 6, to remove a IQueryable subset of the entities. This will mark each of the entities as deleted, and will delete them when the context is saved. This will be more efficient because it does not require you to enumerate the entities first.

using(context db = new context()){
    var items = db.task_Commt.Where(u => u.GlobalId == companyId && u.ItemId == itemId);
    db.task_Commt.RemoveRange(items);
    db.SaveChanges();
}
Brino
  • 2,442
  • 1
  • 21
  • 36
0

Well, functionally this would be the same but it is (arguably) easier to understand what's happening:

 var itemsToDelete = db.task_Commt.Where(u => u.GlobalId == companyId 
                                      && u.ItemId == itemId)
 foreach(var d in itemsToDelete)
     db.task_task_Commt.DeleteObject(d);

Other benefits:

D Stanley
  • 149,601
  • 11
  • 178
  • 240