Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ado.net entity framework delete rows

I may be completely blind and stupid, but I cannot find any method generated by ADO.NET Entity Data Model that would somehow delete rows from my table. I didn't want to create a custom query. So how do I do that? Please help.

I don't have the method DeleteOnSubmit... don't know why. This is the code I wanted to use.

var deleteOrderDetails =
from details in db.OrderDetails
where details.OrderID == 11000
select details;

foreach (var detail in deleteOrderDetails)
{
db.OrderDetails.DeleteOnSubmit(detail);
}

db.SubmitChanges();
like image 833
Trimack Avatar asked Sep 08 '09 14:09

Trimack


People also ask

How do I delete a row in Entity Framework?

Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.

How do I delete a record in Ado net?

To delete a row in the databaseQuery the database for the row to be deleted. Call the DeleteOnSubmit method. Submit the change to the database.

How do I delete all records from a table in Entity Framework?

There are times when we may need to delete all the records from the table using Entity Framework. One of the commonly used ways is to iterate each row and use the DBSet. Remove() .


2 Answers

A couple of alterations needed:

db.DeleteObject(detail);

and

db.SaveChanges();

Kindness,

Dan

PS: Have you been using Linq to SQL and then swapped to the Entity Framework?

like image 193
Daniel Elliott Avatar answered Oct 25 '22 02:10

Daniel Elliott


Here's another way (thanks to this answer)

I assume you have the Orders table, and OrderDetails is related to it via OrderID.

var order = db.Orders.FirstOrDefault(o=> o.OrderID == 11000);
if(order != null)
{
  order.OrderDetails.Clear();
  db.SaveChanges();
}

This should delete all the order details associated with that order.

edit: fixed the code

like image 21
roman m Avatar answered Oct 25 '22 02:10

roman m