Handle Identity columns with SetOutputIdentity
masterWhen performing BulkInsert on tables with Identity columns (e.g., int autoincrement), set SetOutputIdentity = true to have the database-generated IDs updated back into your entity list. This is essential when inserting related parent-child entities where the child needs the parent's new ID as a Foreign Key.
// Recommended pattern for parent-child relationships
using (var transaction = context.Database.BeginTransaction())
{
context.BulkInsert(entities, new BulkConfig { SetOutputIdentity = true });
foreach (var entity in entities) {
foreach (var subEntity in entity.ItemHistories) {
subEntity.ItemId = entity.ItemId; // Sets FK to the generated PK
}
subEntities.AddRange(entity.ItemHistories);
}
context.BulkInsert(subEntities);
transaction.Commit();
}