How to perform delete rows on some condition with EF?

c# entity-framework sql tsql

Question

in ADO.NET I can use delete statement

to delete some rows from an SQL table.

what is the equivalent in Entity Framework?

How can I achieve that same result?

updateing with null objects isn't the same.

1
2
8/19/2015 4:18:44 PM

Accepted Answer

You need to retrieve the object to be deleted first. For example :

 // Assuming ID is primary key in `Customer` entity
 Customer cust = (from c in context.Customers where c.ID = "1" select c);

Then delete the object using DataContext.entity.DeleteObject

 context.Customers.DeleteObject(cust);
 context.SaveChanges();

More : DataContext

1
3/3/2013 11:56:45 AM

Popular Answer

Replies telling you, that you need to first fetch objects (strictly speaking keys are enough, but then you need to do some work manually) into memory and mark them for deletion and finally call SaveChanges. Though that's the "normal" approach, there's bunch of extensions, helpers, ... that allow you to do i.e. batch deletes, batch updates and other helpful stuff.

You can check EntityFramework.Extended (also on GitHub) or Entity Framework Extensions (sources there as well).



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow