简体   繁体   中英

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 directly 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM