Entity Framework Pitfalls: Batch Modifications
Entity Framework does not support batch modifications, that is, UPDATEs or DELETEs of several entities at once. Neither classic nor Code First, not even Entity-SQL.
For UPDATEs, you have to load each entity and modify it to your liking and then save changes.
For DELETEs, you don’t need to load an entity, just call Remove with a proxy entity with an assigned primary key property, like this:
1: var entityToDelete = new MyEntity { Id = 100 };
2: ctx.MyEntities.Remove(entityToDelete);
3: ctx.SaveChanges();
Of course, you can remove several entities at once, just make sure you only call SaveChanges only after Removeing all of them.
Other alternatives exist:
-
Plain old SQL, just call Database.ExecuteSqlCommand;
-
Use a third-party library, such as EntityFramework.Extended, which offers nice strongly-typed methods for both UPDATEs and DELETEs.