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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With