Reputation: 377
I have a parent object which has a list of children object. Plain POCOs, nothing special. EF syntax is one to many.
In my dbcontext, I have the following:
if (parent.childObjectList.Any())
{
foreach (var x in parent.childObjectList)
{
x.Id = 0;
x.ParentId = parent.Id;
}
parent.childObjectList.ForEach(n => _context.ChildObjects.Add(n));
await _context.SaveChangesAsync();
}
EF syntax in model builder:
entity.HasMany(p => p.ChildObject)
.WithOne(e => e.Parent)
.HasForeignKey(p => p.ParentId)
.OnDelete(DeleteBehavior.Restrict);
In the child EF syntax:
entity.HasOne(x => x.Parent)
.WithMany(x => x.ChildObject)
.HasForeignKey(x => x.ParentId)
.OnDelete(DeleteBehavior.NoAction);
When I run this, if there are two childobjects in the list, 4 entries in the db get created. If there are 3 in the list, 6 get created. Where am I wrong in my syntax?
Upvotes: 0
Views: 1396
Reputation: 34653
For one, manually persisting child entities is completely unnecessary. When you create the Parent and new Child instances under it and add the Parent, then call SaveChanges
, the children will automatically be persisted and the FKs will be populated automatically. Also, configuring the relationship only needs to be done on one side. I.e. from parent with a HasMany().WithOne()
, or from the child with a HasOne().WithMany()
, not both.
The typical cause of double entries is when you create entirely new references, setting a PK and FK and adding those entities to another's collection and saving. EF isn't tracking those new instances so it treats them as an insert where you'd expect and update. That doesn't look to be what is happening here, but possibly something similar where by resetting IDs EF is treating these as new instances causing the double-up since if the Parent was already saved, the child records would have been already as well.
Upvotes: 2