gpt4 book ai didi

c# - EF Core 批量扩展 : Index was out of range on BulkInsert

转载 作者:行者123 更新时间:2023-12-02 03:00:31 25 4
gpt4 key购买 nike

我在使用 EF 核心批量扩展的批量插入时收到以下错误:

Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index') at System.Collections.Generic.List1.get_Item(Int32 index) at
EFCore.BulkExtensions.TableInfo.UpdateEntitiesIdentity[T](IList
1 entities, IList1 entitiesWithOutputIdentity) at
EFCore.BulkExtensions.TableInfo.LoadOutputData[T](DbContext context,
IList
1 entities) at EFCore.BulkExtensions.SqlBulkOperation.Merge[T](DbContext context, IList1 entities, TableInfo tableInfo, OperationType operationType,
Action
1 progress) at EFCore.BulkExtensions.DbContextBulkExtensions.BulkInsert[T](DbContext context, IList1 entities, BulkConfig bulkConfig, Action1 progress)
at MyProject.Data.Repository.Repository1.CreateRange(List1 entities)

我有一个父实体和子实体。我想做的是,首先批量插入父级,然后将为父级生成的 Id 分配给其子级。然后批量插入子项。

CreateRange方法:

public List<T> CreateRange(List<T> entities)
{
var bulkConfig = new BulkConfig { PreserveInsertOrder = true, SetOutputIdentity = true };
_dbContext.BulkInsert(entities, bulkConfig);
return entities;
}

批量插入代码:

// Index parents. (Since PreserveInsertOrder = true is set.)
parents.ForEach(x => x.Id = parents.IndexOf(x) + 1);
_parentRepository.CreateRange(parents);

// parent-child relation mapping.
parents.ForEach(x => x.Children.ToList().ForEach(y => y.ParentId = x.Id));

var children = parents.SelectMany(x => x.Children).ToList();
// Index children. (Since PreserveInsertOrder = true is set.)
children.ForEach(x => x.Id = children.IndexOf(x) + 1);
_childRepository.CreateRange(children);

并不总是能够重现此问题。我无法确定重现此问题的条件。

最佳答案

该异常是由于批量插入操作之前分配的Id与数据库中已存在的Id冲突所致。解决方案是使用数据库中没有的 Id。例如,负数。这仍然可以保留插入顺序,因为重要的是要插入的列表中实体之间的相对顺序。

修改后的代码:

// Index parents with non-conflict keys. (Since PreserveInsertOrder = true is set.)
parents.ForEach(x => x.Id = parents.IndexOf(x) - parents.Count);
_parentRepository.CreateRange(parents);

// parent-child relation mapping.
parents.ForEach(x => x.Children.ToList().ForEach(y => y.ParentId = x.Id));

var children = parents.SelectMany(x => x.Children).ToList();
// Index children with non-conflict keys. (Since PreserveInsertOrder = true is set.)
children.ForEach(x => x.Id = children.IndexOf(x) - children.Count);
_childRepository.CreateRange(children);

关于c# - EF Core 批量扩展 : Index was out of range on BulkInsert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60087448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com