I’m currently working on an app using EF 4.1 Code First and have a question about how to save a new object with child objects from another context. The Context is stored in request mode.
I create a new object called ‘Vacancy’. The user is then prompted to add locations to the Vacancy’s collection of locations. The locations are pulled through the context and preferably I would like to avoid saving locations added to the Vacancy back to the database until the user is finished which could potentially be after several postbacks.
Problem is that the Locations are from a context that does no longer exist so trying to save my vacancy will throw an error.
I’m sure this is a common problem and I hope there is a good way to handle this.
Kind regards,
You must detach each entity you want to store (probably in session) among multiple requests.
You should be also able to completely avoid this if you turn off proxy creation for loading of these entities and load them as no tracking.
Be aware that during the save you will have to tell EF that those entities are existing one by again correctly setting their state otherwise EF will try to insert them again.