I have a one to many relationship and I'm trying to copy them.
var context = this._dbContextProvider.GetDbContext();
var parent = await context.Parents
.Include(p => p.Childs)
.FirstOrDefaultAsync(p => p.Id == inputParentId);
var copiedParent = parent;
copiedParent.Id = Guid.Empty;
List<Child> c = new List<Child>();
foreach (var child in copiedCaptureTemplate.childs)
{
var copiedChild = child;
copiedChild.Id = Guid.Empty;
copiedChild.ParentId = Guid.Empty;
c.Add(copiedChild);
}
copiedParent.Childs = null;
var createdParent = await context.Parents.AddAsync(copiedParent);
context.SaveChanges();
//loop on list c to add on the new parentId's
//add that list to the createParent and SaveChanges
There is propbably a better way to deep copy, but I imagined this would work. However when I addAsync I get the error:
The property 'Id' on entity type 'Child' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principal.
The entity Parent has:
public ICollection<Child> Childs { get; set; }
The entity Child has:
public virtual Guid ParentId { get; set; }
public Parent Parent{ get; set; }
PortalDbContext has:
modelBuilder.Entity<Parent>()
.HasMany(p => p.Childs)
.WithOne(c => c.Parent)
.HasForeignKey(c => c.ParentId);