0

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.

2
  • An existing object has no key that can identify it (when it comes back to the service)? Commented Mar 6, 2013 at 10:02
  • It has, all objects have keys - keys are generated on the client. Commented Mar 6, 2013 at 10:11

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.