Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a list of object using ObjectContext?

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.

like image 666
Joe.wang Avatar asked Dec 14 '12 06:12

Joe.wang


2 Answers

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.

like image 147
Nguyen Van Thanh Avatar answered Oct 12 '22 18:10

Nguyen Van Thanh


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();
like image 32
iGanja Avatar answered Oct 12 '22 20:10

iGanja