0

I'm wanting to deep clone and then save the new new entities like so however the foreign key PropertyId on PropertyInfo should be altered to reference the newly created Property - Is there a convenient approach to do achieve this?

The reported duplicate question does not address my problem, it answers how to deep clone an entity but not how to update the FK on an associated entity.

var originalEntity = Context.Property.Include("PropertyInfo")
                        .AsNoTracking()
                        .FirstOrDefault(e => e.Id == 1);


 Context.Properties.Add(originalEntity);
J.Doe
  • 1
  • 1
  • Possible duplicate of [Entity Framework 5 deep copy/clone of an entity](https://stackoverflow.com/questions/15308747/entity-framework-5-deep-copy-clone-of-an-entity) – Sani Huttunen Aug 20 '19 at 16:08
  • @SaniSinghHuttunen This isn't a duplicate of the suggested post, the post doesn't answer alter the FK on the associated entities. – J.Doe Aug 20 '19 at 16:10
  • @J.Doe You may have to do that separately, clone `Property`, call `SaveChanges` to generate the new entity's `PropertyId` then clone `PropertyInfo`, assign it the new `PropertyId` and `SaveChanges` again. – Canica Aug 20 '19 at 16:13
  • @J.Doe: Look at [this answer](https://stackoverflow.com/a/54512362/26742) which seem to be exactly what you ask for. – Sani Huttunen Aug 20 '19 at 16:16
  • @J.Doe added an answer – Gabriel Llorico Aug 21 '19 at 04:35

1 Answers1

0

Remove Primary Ids

var originalEntity = Context.Property.Include("PropertyInfo")
                        .AsNoTracking()
                        .FirstOrDefault(e => e.Id == 1);


originalEntity.Id = 0;
//either create propertyinfo or assign propertyinfo
originalEntity.PropertyInfo = createdPropertyInfo || Context.PropertyInfo.First(x => x.Id == idOfFKPropertyInfo);

 Context.Properties.Add(originalEntity);
Gabriel Llorico
  • 1,783
  • 1
  • 13
  • 23