EF Core Bulk Insert is not updating the expected database generated IDs

667 views Asked by At

I'm using the EFCore.BulkExtensions lib version 6.7.0 and Entity Framework Core v6.0.13, trying to reproduce the following behaviour explained in the docs:

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 match its linked PK that was generated in DB
        }

        subEntities.AddRange(entity.ItemHistories);
    }

    context.BulkInsert(subEntities);
    transaction.Commit();
}

The entity.ItemId is supposed to be updated with the PK generated by the database.

I couldn't reproduce it with the following code, the result is always: [ENTITY ID]: 0

using (var transaction = dbContext.Database.BeginTransaction())
{
    var entities = entitiesEnumerable.ToList();

    foreach (var e in entities)
    {
        e.Id = default;
    }

    var bulkConfig = new BulkConfig
    {
        SetOutputIdentity = true
    };

    await dbContext.BulkInsertAsync(entities, bulkConfig);

    foreach (var e in entities)
    {
        _logger.LogWarning($"[ENTITY ID]: {e.Id}");
    }

    transaction.Commit();
}

My entity has the following attribute as PK and the underlying database is SQL Server:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
1

There are 1 answers

0
borisdj On

Try to move transaction.Commit(); before last foreach loop. For other Q, you can make and issue on the Git repo.