dbContext.Database.ExecuteSqlCommand("delete from MyTable");
(Do not joke.)
The problem is that EF does not support command commands and the only way to delete all objects in a collection without direct DML is:
foreach (var entity in dbContext.MyEntities) dbContext.MyEntities.Remove(entity); dbContext.SaveChanges();
Or maybe a little cheaper not to download full objects:
foreach (var id in dbContext.MyEntities.Select(e => e.Id)) { var entity = new MyEntity { Id = id }; dbContext.MyEntities.Attach(entity); dbContext.MyEntities.Remove(entity); } dbContext.SaveChanges();
But in both cases, you need to load all entities or all properties and delete objects one by one from the set. Moreover, when you call SaveChanges , EF will send n (= the number of entities in the set) DELETE statements to the database, which are also executed one after the other in the database (in one transaction).
So, direct SQL is clearly preferable for this purpose, since you only need one DELETE statement.
Slauma May 4 '12 at 2:32 pm 2012-05-04 14:32
source share