Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete an object from an Entity Framework model without first loading it?

I am quite sure I've seen the answer to this question somewhere, but as I couldn't find it with a couple of searches on SO or google, I ask it again anyway...

In Entity Framework, the only way to delete a data object seems to be

MyEntityModel ent = new MyEntityModel(); ent.DeleteObject(theObjectToDelete); ent.SaveChanges(); 

However, this approach requires the object to be loaded to, in this case, the Controller first, just to delete it. Is there a way to delete a business object referencing only for instance its ID?

If there is a smarter way using Linq or Lambda expressions, that is fine too. The main objective, though, is to avoid loading data just to delete it.

like image 219
Tomas Aschan Avatar asked Feb 02 '09 10:02

Tomas Aschan


People also ask

How do I delete multiple rows in Entity Framework?

RemoveRange. The RemoveRange method is used for deleting multiple objects from the database in one method call. The following code deletes a large number of records from the database using RemoveRange.


2 Answers

It is worth knowing that the Entity Framework supports both to Linq to Entities and Entity SQL. If you find yourself wanting to do deletes or updates that could potentially affect many records you can use the equivalent of ExecuteNonQuery.

In Entity SQL this might look like

   Using db As New HelloEfEntities          Dim qStr = "Delete " & _                   "FROM Employee"         db.ExecuteStoreCommand(qStr)         db.SaveChanges()     End Using 

In this example, db is my ObjectContext. Also note that the ExecuteStoreCommand function takes an optional array of parameters.

like image 190
John Wigger Avatar answered Sep 28 '22 12:09

John Wigger


I found this post, which states that there really is no better way to delete records. The explanation given was that all the foreign keys, relations etc that are unique for this record are also deleted, and so EF needs to have the correct information about the record. I am puzzled by why this couldn't be achieved without loading data back and forth, but as it's not going to happen very often I have decided (for now) that I won't bother.

If you do have a solution to this problem, feel free to let me know =)

like image 30
Tomas Aschan Avatar answered Sep 28 '22 11:09

Tomas Aschan