What's the best way to remove all elements in a System.Data.Entity.DbSet, with Entity Framework 4.3?
Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database. So it makes perfect sense that you will get a combination of both!
Methods. Add(TEntity) Adds the given entity to the context underlying the set in the Added state such that it will be inserted into the database when SaveChanges is called.
DbContext is your UoW (Unit of Work) and each DbSet is the repository.
dbContext.Database.ExecuteSqlCommand("delete from MyTable");
(No kidding.)
The problem is that EF doesn't support any batch commands and the only way to delete all entities in a set using no direct DML would be:
foreach (var entity in dbContext.MyEntities) dbContext.MyEntities.Remove(entity); dbContext.SaveChanges();
Or maybe a litte bit cheaper to avoid loading full entities:
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 have to load all entities or all key properties and remove the entities one by one from the set. Moreover when you call SaveChanges
EF will send n (=number of entities in the set) DELETE statements to the database which also get executed one by one in the DB (in a single transaction).
So, direct SQL is clearly preferable for this purpose as you only need a single DELETE statement.
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