We have just done a merge to EF7 from EF6, since we use ASP.Net 5 in our application. The project is just started, so we won't run into issues with releasing code dependent on beta libraries.
We have run into an issue with cascading inserts. By cascading inserts I mean that a collection of child entities is inserted / updated with the parent. It seems to be dependent on the order of operations in a surprising way.
Given the following definitions:
public class ParentEntity
{
public int Id { get; set; }
public ICollection<ChildEntity> Children { get; set; }
}
public class ChildEntity
{
public int Id { get;set; }
public ParentEntity Parent { get; set; }
}
the following code works (ChildTable is populated with 3 values):
var parent = new ParentEntity();
parentSet.Add(parent);
parent.Children = new List<ChildEntity>();
for (int i = 0; i < 3; i++)
{
var child= new ChildEntity { Parent = parent };
parent.Children.Add(child);
}
_uow.SaveChanges();
But the following does not (ChildTable remains empty):
var parent = new ParentEntity();
// Moved parentSet.Add()
parent.Children = new List<ChildEntity>();
for (int i = 0; i < 3; i++)
{
var child= new ChildEntity { Parent = parent };
parent.Children.Add(child);
}
parentSet.Add(parent);
_uow.SaveChanges();
To make the below work, I have to do the following:
var parent = new ParentEntity();
parent.Children = new List<ChildEntity>();
for (int i = 0; i < 3; i++)
{
var child= new ChildEntity { Parent = parent };
parent.Children.Add(child);
childSet.Add(child); // Added childSet.Add()
}
parentSet.Add(parent);
_uow.SaveChanges();
Can someone explain why there is such a difference? In EF6, this works as I expect it to. I would understand if there wasn't support yet in EF7 for automatically tracked child entities, but obviously you can make it work if you move the Set.Add call around. It is even more surprising to me that moving the Set.Add call to ahead of when the child collection is populated is what works.
Any ideas / explanations?
We use EF7 beta 7.