EF Core Bulk Insert 没有更新预期的数据库生成的 ID

问题描述 投票:0回答:0

我正在使用 EFCore.BulkExtensions lib 版本 6.7.0 和 Entity Framework Core v6.0.13,试图重现文档中解释的以下行为:

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();
}

entity.ItemId
应该用数据库生成的PK更新。

我无法用下面的代码重现它,结果总是:

[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();
}

我的实体有如下属性作为PK,底层数据库是SQL Server:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
c# entity-framework .net-core efcore.bulkextensions
© www.soinside.com 2019 - 2024. All rights reserved.