We're creating a WebAPI using Entity Framework in MVC 4. Our client wants to send complex objects containing related objects - both new and updated. The root object maybe new or existing one too. The client generates primary keys - we're using Guids for that. So on server we really can't tell that we got an existing object update or a new one. What would be the best way to handle this situation? We need some sort of add or update functionality and it's not yet clear to us how to proceed with Entity Framework for this.
-
An existing object has no key that can identify it (when it comes back to the service)?Neil Thompson– Neil Thompson2013-03-06 10:02:09 +00:00Commented Mar 6, 2013 at 10:02
-
It has, all objects have keys - keys are generated on the client.devmiles.com– devmiles.com2013-03-06 10:11:49 +00:00Commented Mar 6, 2013 at 10:11
Add a comment
|
1 Answer
EF doesn't have any build in support for discovering changes in detached object graph. You either have to include some field into every object describing if the object is new, not modified, updated or deleted (you will also need similar behavior to track changes in many-to-many relationships). If you don't use such field you have no other way than querying database and comparing current DB state with data received from client to find what has changed.
3 Comments
devmiles.com
Yeah, I know we'll have to query for existence first, no way around that, I'm looking for the best way to force this behavior for all operations we perform on complex objects we get from the client. Even if I had a special field marking the object new or updated, how would I check this field for all my entities in one place?
Ladislav Mrnka
If you browse other answers in the linked question somebody claims to have reusable solution for this problem and provides code on github. The best description of using additional fields is in the book EF Programming DbContext. Generally you can implement some interface exposing the flag on every entity and in overriden
SaveChanges fix states of entities.devmiles.com
I'm accepting your answer, we've ended up writing our own procedure that carefully saves our domain object graphs. Your linked question and answers to it were really helpful though! Thanks a lot!