Deep cloning objects with children

234 Views Asked by At

I’m looking for a solution were I can copy an object with several levels of children, update the primary key (and foreign key of the children) and save it on the DB again. Just so I can have an exact copy of the whole object but with a new key.

I tried using ValueInjuecter and it does create a deep copy but I don’t know how to update the foreign keys of the children to make them point to the newly created object.

I also tried AutoMapper and something similar happens.

Does anyone know how I can get this done?

2

There are 2 best solutions below

0
Jimmy Bogard On

Just write manual code to do the copying. It'll probably take you 30 minutes or so. You can also try using .NET's cloning with a BinaryFormatter, but that won't help with your PK/FK issues.

0
Nikola.Lukovic On

Probably the best and most performant solution is to create your own library that would use MemberwiseClone recursively for every child.