I am inserting or updating a parent entity with associated children entities. Entity framework inserts or updates the entities BUT it never creates or updates the links between them even though they exist in C#.
public void MergeParent(Parent parent)
{
// Set Parent
var parentInDB = context.Parents.SingleOrDefault(p => p.ParentID == parent.ParentID);
if (parentInDB != null)
{
parent.ID = parentInDB.ID;
context.Entry(parentInDB).CurrentValues.SetValues(parent);
}
else
{
context.parents.Add(parent);
}
// Set child
foreach(var child in parent.children)
{
var childInDB = context.children.SingleOrDefault(a => a.DiscogsID == child.DiscogsID && child.DiscogsID != null);
if (childInDB != null)
{
child.ID = childInDB.ID;
context.Entry(childInDB).CurrentValues.SetValues(child);
}
else
{
context.children.Add(child);
}
}
// Finally Save
context.SaveChanges();
}
If I set a breakpoint, I can see the parent has the children associated, but while the database contains the elements it does not ever update the link table.