How to DELETE multiple items from database with Code-First EF 4.1
We use code-first EF 4 with DbContext and DbSet<> and POCOs with DataAnnotations. I am new to this and cannot seem to find an answer to my quesiton:
How can I delete multiple items from the DB dir开发者_运维百科ectly without first selecting the items with LINQ and then doing loop and call Remove(item)
on each iteration? That seems silly to me.
All references concerning this refer to function that don't seem to exist, like DeleteOnSubmit(item)
which isn't there in my DbContext. Also, it only deletes ONE item.
Is there a better way?
DeleteOnSubmit
is function from DataContext
class = Linq-to-SQL
Yo don't have to load item before you delete it. It is enough if you know its key. Something like this should work:
var item = new Item { Id = someId };
context.Items.Attach(item);
context.Items.Remove(item);
context.SaveChanges();
or
var item = new Item { Id = someId };
context.Items.Attach(item);
context.Entry(item).State = EntityState.Deleted;
context.SaveChanges();
There is no way to delete multiple items with EF (except cascade delete) without specifying each single item to be deleted. If you want to deleted multiple items directly you must use SQL like
context.Database.ExecuteSqlCommand("DELETE ...");
Entity framework doesn't support multiple deletion at once as it required object in memory. You need to iterate through loop.
精彩评论