How to delete a list of object using ObjectContext?
The accepted answer above is outdated as the syntax has been deprecated in favor of deleting a simple query instead:
db.Customers.Where(c => c.State == '-1').Delete();
You can use EntityFramework.Extended library, which is available from Nuget (don't forget to add using EntityFramework.Extensions;
):
db.Customers.Delete(c => c.State == '-1');
Or you can write extension method manually:
public static void DeleteObjects<T>(this ObjectSet<T> set,
IEnumerable<T> entities)
where T : EntityObject
{
foreach (var entity in entities)
set.DeleteObject(entity);
}
Usage:
var customersToDelete = db.Customers.Where(c => c.State == '-1');
db.Customers.DeleteObjects(customersToDelete);
Or better one:
public static void DeleteObjects<T>(this ObjectSet<T> set,
Expression<Func<T, bool>> predicate)
where T : EntityObject
{
foreach (var entity in set.AsQueryable<T>().Where(predicate))
set.DeleteObject(entity);
}
Usage:
db.Customers.DeleteObjects(c => c.State == '-1');