What I would like to do is duplicate/copy my School
object and all of its children/associations in EF Core
I have something like the following:
var item = await _db.School
.AsNoTracking()
.Include(x => x.Students)
.Include(x => x.Teachers)
.Include(x => x.StudentClasses)
.ThenInclude(x => x.Class)
.FirstOrDefaultAsync(x => x.Id == schoolId);
I have been reading up on deep cloning and it seems that I should be able to do just add the entity...so pretty much the next line.
await _db.AddAsync(item);
Then EF should be smart enough to add that entity as a NEW entity. However, right off the bat I get a conflict that says "the id {schoolId} already exists" and will not insert. Even if I reset the Id of the new item I am trying to add, I still get conflicts with the Ids of the associations/children of the school iteam.
Is anyone familiar with this and what I might be doing wrong?
item.Id == Guid.NewGuid()
you are not setting the property, you are checking for equality. I'm assuming you aren't actually setting the property to a different value prior to saving. Show more of the code you are running so we can better help, but at first glance this looks to be the issue. – Dan D Feb 19 '18 at 20:33Add
, the entities with non default PKs (e.g. 0,Guid.Empty
etc.) will be considered as existing. I'm afraid "deep cloning" is not EF Core target. See Disconnected Entities. – Ivan Stoev Feb 19 '18 at 20:40TrackGraph
method to simulate forcedAdd
. Inside the callback you have to set the entity PK todefault(Guid)
and state toAdded
. – Ivan Stoev Feb 20 '18 at 8:20