How to avoid clashes with existing entity ID's when deserializing and importing EF entities?
I have an ASP.NET 4 web app that is using the Entity Framework to hold, amongst other things, a hierarchical structure of items that is used for features such as navigation.
One of the functions of the application allow开发者_高级运维s the export of a particular branch of the hierarchy tree to XML, generated using a DataContractSerializer. Once exported, the intention is that the XML can then be uploaded to another instance of the same app, deserialized back into EF objects and then added to the data model on the second server.
When I try and import data in this way, I'm finding that I see the following error:
The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object.
Taking a closer look at the XML that is generated by the serializer, I can see that the entity key is among the items that has been serialized. Since I'm importing entities that originate from a different database, some of the ID's clash.
What I'd ideally like to be able to do (unless I'm missing something here) is attach the imported entities to an object context and reset the ID's of the objects being imported.
Is there a smart way to do this? Do I simply have to set the ID for each of my imported entities to 0, attach them to the object context and then save changes?
Thanks in advance!
Ok managed to get there myself in the end. What I had to do for each entity was as follows:
- Set the identity property to 0.
- Set the EntityKey property to null.
- For each property on the entity derived from EntityReference, set the EntityKey on that reference to null.
I then added the root node in the hierarchy I was importing to my object context using AddObject and called SaveChanges.
精彩评论