Como copiar em profundidade uma entidade
Encontrei este trechoaqu:
public static T DeepClone<T>(this T obj)
{
using (var ms = new MemoryStream()) {
var bf = new BinaryFormatter();
bf.Serialize(ms, obj);
ms.Position = 0;
return (T)bf.Deserialize(ms);
}
}
O que diz que podemos fazer cópias profundas de todos os objetos relacionados por meio diss
Estou tentando fazer uma cópia assim:
db.Detach(myEntity);
myEntity.EntityKEy = null;
Entity newEntity = new Entity();
newEntity = DeepClone<Entity>(Entity);
db.Entities.AddObject(newEntity);
db.SaveChanges();
IT funciona, mas ainda não copia nenhum registro aninhado \ relacionado. o que faço de errado aqui?
Eu tenho essa estrutura Entidade-> ChildEntity -> ChildChildEntity
-> - um para muitos
Assumo que, quando copio a entidade, ele também copia todos os registros filh
ATUALIZAR Após sugestões, fiz o seguinte:
Entity newEntity = new Entity();
Eneity Entity = db.Include("ChildEntity").Where(p=>p.Id==Id).Single();
newEntity = DeepClone<Entity>(Entity);
db.Detach(myEntity);
myEntity.EntityKEy = null;
db.Entities.AddObject(newEntity);
db.SaveChanges();
Obtendo exceção na linha AddObject:
Um objeto com a mesma chave já existe no ObjectStateManager. O ObjectStateManager não pode rastrear vários objetos com a mesma chav