Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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();
db.Customers.Where(c => c.State == '-1').ToList().ForEach(db.DeleteObject);
db.SaveChanges();

should be all you need.

Entity Framework Core

3.1 3.0 2.2 2.1 2.0 1.1 1.0

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

Summary:

Removes the given collection of entities from the context underlying the set with each entity being put into the Deleted state such that it will be deleted from the database when SaveChanges is called.

Remarks:

Note that if System.Data.Entity.Infrastructure.DbContextConfiguration.AutoDetectChangesEnabled is set to true (which is the default), then DetectChanges will be called once before delete any entities and will not be called again. This means that in some situations RemoveRange may perform significantly better than calling Remove multiple times would do. Note that if any entity exists in the context in the Added state, then this method will cause it to be detached from the context. This is because an Added entity is assumed not to exist in the database such that trying to delete it does not make sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top