How can I remove an object from an Entity Framework model without having to load it first? entity-framework linq-to-entities


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();

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.

2/2/2009 10:38:02 AM

Accepted Answer

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"
    End Using

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

5/4/2017 9:30:43 AM

Popular Answer

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 =)

Related Questions


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