Reputation: 36654
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.
Upvotes: 4
Views: 14101
Reputation: 3512
First of all you need to create instance from your Database entities,after that you should select your desired object,then delete it :
TestEntities db = new TestEntities();
Test ts = (from rows in db.Tests
where rows.ID == 1
select rows).FirstOrDefault();
if (ts != null)
{
db.Tests.DeleteObject(ts);
db.SaveChanges();
}
Update :
If your result set is a list, I mean more than one record you can use this solution :
List<Test> lst = (from rows in db.Tests select rows).ToList();
foreach (Test item in lst)
{
db.Tests.DeleteObject(item);
}
db.SaveChanges();
Upvotes: 0
Reputation: 4150
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).
Upvotes: 3
Reputation: 18569
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
Upvotes: 2