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

36,663

Solution 1

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.

Solution 2

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

Solution 3

You can create an object with the same id and pass it through to the delete BUT its good for simple objects if you have complex relations you may need more than that

                var user = new User { ID = 15 };
                context.Entry(user).State = EntityState.Deleted;
                context.SaveChanges();

Solution 4

Apologies in advance, but I have to question your goal.

If you delete an object without ever reading it, then you can't know if another user has changed the object in between the time you confirmed that you wanted to delete the object and the actual delete. In "plain old SQL", this would be like doing:

DELETE FROM FOO
WHERE ID = 1234

Of course, most people don't actually do this. Instead, they do something like:

DELETE FROM FOO
WHERE ID = 1234
  AND NAME = ?ExpectedName AND...

The point is that the delete should fail (do nothing) if another user has changed the record in the interim.

With this, better statement of the problem, there are two possible solutions when using the Entity Framework.

  1. In your Delete method, the existing instance, compare the expected values of the properties, and delete if they are the same. In this case, the Entity Framework will take care of writing a DELETE statement which includes the property values.

  2. Write a stored procedure which accepts both the IDE and the other property values, and execute that.

Solution 5

There's a way to spoof load an entity by re-calculating it's EntityKey. It looks like a bit of a hack, but might be the only way to do this in EF.

Blog article on Deleting without Fetching

Share:
36,663
Tomas Aschan
Author by

Tomas Aschan

I am an engineering physicist from Stockholm, Sweden, with a passionate interest in programming and software architecture. Since creating my first program at age 12 (a VB6 app that showed a smiley when a button was clicked) I've spent many hours in front of my computer, watching screen casts and reading blogs about programming as well as trying all the new concepts out in my own programs. With a Master's degree in Engineering Physics from the Royal Institute of Technology in Stockholm, Sweden, I have deepened my modelling and reasoning skills, as well as had the opportunity to try out many different technologies and tools. I am currently working as a software engineer at Spotify, mostly massaging data to enable our internal research into developer productivity.

Updated on May 04, 2020

Comments

  • Tomas Aschan
    Tomas Aschan about 4 years

    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.