我正在使用 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; }