简体   繁体   中英

LINQ Delete multiple rows

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);

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();
}

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM