Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I remove all elements in a DbSet?

What's the best way to remove all elements in a System.Data.Entity.DbSet, with Entity Framework 4.3?

like image 709
aknuds1 Avatar asked May 04 '12 12:05

aknuds1


People also ask

What is the difference between DbSet and DbContext?

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!

What is DbSet TEntity?

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.

Is DbSet a repository?

DbContext is your UoW (Unit of Work) and each DbSet is the repository.


1 Answers

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.

like image 187
Slauma Avatar answered Sep 27 '22 19:09

Slauma