In your specific example you are turning on identity inserts for the parent table but not the child table. If you want to do both then you'd need to turn it off for both tables. But this is a bad idea. You should really never need to do this short of a disaster recovery situation where you need to restore rows that are no longer available and for which you cannot change their IDs.
Why are you doing this at all? In general if you have defined the relationship properly in EF then EF will handle setting parent/child relationships automatically for you. You don't need (nor should) manage IDs manually). Specifically, in your code the child table rows will always have the wrong IDs after the first run of that code. You shouldn't be setting the IDs at all. Given your models, set the Parent
property of the child to the Parent
object you created and EF will handle inserting the parent and children and fixing up their IDs and relationships automatically.
Not tested, but something like this should be sufficient.
async Task AddEntitiesAsync ()
{
var entities = new[]
{
new
{
ParentCell = "AA1",
ChildCells = new[] { "BB11", "BB12" }
},
new
{
ParentCell = "AA2",
ChildCells = new[] { "BB21", "BB22", "BB23" }
}
};
foreach(var entity in entities)
{
//Create the parent EF object
var parentEntity = context.ParentDbSet.Add(new Parent() {
ParentCell = entity.ParentCell
});
//Create the children
foreach (var child in entity.ChildCells)
{
//I prefer to add the entities directly to the DbSets
//but an alternative is to simply add the children to parentEntity.Children, has same effect
context.ChildDbSet.Add(new Child() {
ChildCell = child,
Parent = parentEntity
});
};
};
//Save the changes
await context.SaveChangesAsync();
}
The parent will be added and its Id set automatically by EF. The children will be created and the Id they will use will be set by DB. The parent of the child will be set because the parent is automatically updated.
To make sure EF knows the Id properties are set automatically then you should add the following to your table configurations for both tables (or use the data annotations).
entity.HasKey(x => x.Id);
This tells EF to get the value after inserting a new object because the DB is going to generate it automatically.