3

The following statement should delete someCars from allCars, and it works, however I was wondering if there is a better solution which specifically uses only linq

foreach (var car in someCars) 
{
    db.allCars.DeleteObject(car); 
}

Note that db is the instance of the db entities.

Any help would be much appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
alexchet
  • 479
  • 1
  • 5
  • 14
  • possible duplicate of [How do I delete multiple rows in Entity Framework (without foreach)](http://stackoverflow.com/questions/2519866/how-do-i-delete-multiple-rows-in-entity-framework-without-foreach) – Arion Jan 10 '13 at 13:28

3 Answers3

5

You can use EntityFramework.Extended library to delete entities based on some condition (library available from Nuget):

db.allCars.Delete(car => /*condition*/);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
4

using Linq as ForEach:

db.allCars.Where(/* condition */).ToList().ForEach(car => db.allCars.Remove(car));

in the same line of this answer :) , How do I delete multiple rows in Entity Framework (without foreach)

Community
  • 1
  • 1
Shady
  • 364
  • 5
  • 18
0

You can use:

db.allCars.RemoveAll(db.allCars.Where(/* condition */));
ruffen
  • 1,695
  • 2
  • 25
  • 51
  • Hi thanks for the quick response. I have indeed tried this before coming here, however it was taking to much time (Over a minute) to excute. – alexchet Jan 10 '13 at 13:41
  • I believe the reason this takes so long to execute is the value is never cached. As an IEnumberable, it is grabbed from the db for every iteration. So for each car that is deleted, it gathers every car in the database before deleting the next one. This can be solved with a `.ToList()` after the `Where` clause, assuming I am correct. – James G. Jul 01 '15 at 19:04