How can I remove an object from an Entity Framework model without having to load it first?

asp.net-mvc entity-framework linq-to-entities

Question

Even though I'm very sure I've read the solution to this question someplace, I'm asking it again since SO and Google searches didn't turn it up.

The only method to remove a data object from Entity Framework seems to be

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

But in order to remove an object using this method, it must first be loaded into the Controller in this scenario. Is it possible to remove a business item by just referencing its ID, for example?

It's okay if there is a more intelligent solution that makes use of Linq or Lambda expressions. But avoiding importing data simply to erase it is the key goal.

1
39
2/2/2009 10:38:02 AM

Accepted Answer

It is important to be aware that the Entity Framework supports both Entity SQL and Linq to Entities. If you wish to make adjustments or deletions that might possibly effect a lot of data, use the equivalent ofExecuteNonQuery .

This may appear as follows in Entity SQL:

   Using db As New HelloEfEntities

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

In this instance,db is myObjectContext . Note as well that theExecuteStoreCommand function accepts a variable array of arguments.

19
5/4/2017 9:30:43 AM

Popular Answer

There actually isn't a better method to erase records, according to these words, which I discovered. The justification offered was that any foreign keys, relations, etc. that are exclusive to this record are likewise erased, necessitating the accurate knowledge of the record on the part of EF. Although it baffles me why this couldn't be done without loading data back and forth, I've opted not to worry (for the time being) since it won't happen very often.

Please let me know if you do have a solution to this issue =)



Related Questions





Related

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