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);
1
  • Why do you think it deletes more than the Where returns? Doesn't seem likely. Commented May 26, 2015 at 20:20

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.