How to Bulk Update records in Entity Framework?
Use ExecuteSqlCommand
:
using (yourDbEntities db = new yourDbEntities())
{
db.Database.ExecuteSqlCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
}
Or ExecuteStoreCommand
:
yourDbContext.ExecuteStoreCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first :
using (myDbEntities db = new myDbEntities())
{
try
{
//disable detection of changes to improve performance
db.Configuration.AutoDetectChangesEnabled = false;
//for all the entities to update...
MyObjectEntity entityToUpdate = new MyObjectEntity() {Id=123, Quantity=100};
db.MyObjectEntity.Attach(entityToUpdate);
//then perform the update
db.SaveChanges();
}
finally
{
//re-enable detection of changes
db.Configuration.AutoDetectChangesEnabled = true;
}
}
Use this way if you just want to modify few properties:
foreach (var vSelectedDok in doks)
{
//disable detection of changes to improve performance
vDal.Configuration.AutoDetectChangesEnabled = false;
vDal.Dokumente.Attach(vSelectedDok);
vDal.Entry(vSelectedDok).Property(x=>x.Status).IsModified=true;
vDal.Entry(vSelectedDok).Property(x => x.LastDateChanged).IsModified = true;
}
vDal.SaveChanges();