Reputation: 693
I'm using the latest version of EF and trying to work out how to make a copy of an object and insert it as a new record, but so that all the properties of the object that point to different objects still point to those objects after the copy.
So I have say a 'software' object that has a version and has author and company properties, I make a copy of this bit of software and update the version, the author and company remain the same but I have a new record for it. So technically I would be able to roll back to a previous version if I needed to.
Currently fetching the object, updating it and inserting it as new creates new versions of the linked objects which is expected. I understand you can attach and detach objects to the context which seems to be the right sort of approach but not sure how that works when you want a new record.
Thanks
Upvotes: 1
Views: 911
Reputation: 10416
When you're updating the object, prior to calling SaveChanges(), you can modify the EntityState to added, so EF will then add the entity as new, rather than updating the existing entity.
If you have a DbContext:
YourContext.Entry(YourEntity).State = EntityState.Added;
If you have an ObjectContext:
YourContext.ObjectStateManager.ChangeObjectState(YourEntity, EntityState.Added);
Upvotes: 4