How to delete a list of object using ObjectContext?

Joe.wang picture Joe.wang · Dec 14, 2012 · Viewed 26.7k times · Source

Say you have code like this .

using (CustomerContext db = new CustomerContext())
{
   var foundCustList=db.Customers.Where(c=>c.State=='-1').ToList();//Find all the customer which State is -1
   foreach(var c in foundCustList)
   {
       db.DeleteObject(c);
   }
   db.SaveChanges();//After all the customer is deleted, Commit.
}

But I want to know Is there any way to delete the list of object easily? I don't want to use the foreach to do it one by one for a list . thanks.

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Dec 14, 2012

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