提问人:HimuQAQ 提问时间:10/20/2023 更新时间:10/20/2023 访问量:57
无法通过 EFCore.BulkExtensions.BulkInsert 插入实体,但出现异常:字典中不存在给定的键“xxx”
Cannot insert entities by EFCore.BulkExtensions.BulkInsert with Exception: The given key 'xxx' was not present in the dictionary
问:
当我尝试使用 插入批量数据时,我遇到了以下异常:EFCore.BulkExtensions.BulkInsert
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Collections.Generic.KeyNotFoundException: The given key 'EnglishWordId' was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at EFCore.BulkExtensions.TableInfo.LoadData[T](DbContext context, Type type, IEnumerable`1 entities, Boolean loadOnlyPKColumn)
at EFCore.BulkExtensions.TableInfo.CreateInstance[T](DbContext context, Type type, IEnumerable`1 entities, OperationType operationType, BulkConfig bulkConfig)
at EFCore.BulkExtensions.DbContextBulkTransaction.ExecuteAsync[T](DbContext context, Type type, IEnumerable`1 entities, OperationType operationType, BulkConfig bulkConfig, Action`1 progress, CancellationToken cancellationToken)
at Identity.Controllers.ImportDictionaryController.ImportDictionaryToDatabase(String connectionId, Stream stream) in C:\Code\Dotnet\Identity\Identity\Controllers\ImportDictionaryController.cs:line 56
at Identity.Controllers.ImportDictionaryController.UploadDictionaryFile() in C:\Code\Dotnet\Identity\Identity\Controllers\ImportDictionaryController.cs:line 37
at Identity.Controllers.ImportDictionaryController.UploadDictionaryFile() in C:\Code\Dotnet\Identity\Identity\Controllers\ImportDictionaryController.cs:line 37
// ...
我正在尝试使用 EFCore 将解析的 CSV 数据导入数据库。
这是我尝试将数据插入数据库的代码的一部分:
var words = await csv.GetRecordsAsync<EnglishWord>().ToListAsync();
long totalCount = words.Count;
for (int count = 0; count < totalCount; count += 100)
{
var inserted = words.Skip(count).Take(100);
await _dictionaryContext.BulkInsertAsync(inserted, config =>
{
config.PreserveInsertOrder = true;
config.SetOutputIdentity = true;
});
// Console.WriteLine($"({connectionId}) Processing: {count} / {totalCount}");
}
这是我的实体类的相关定义,数据库已经完成了迁移和更新。
public class EnglishWord
{
public long EnglishWordId;
public string Word = null!;
public string? Phonetic;
public string? Definition;
public string Translation = null!;
}
注意:不会为每个 EnglishWord 设置id,这意味着var words = await csv.GetRecordsAsync<EnglishWord>().ToListAsync();
words[0] = ... words[n-1].EnglishId = 0 (defalut value)
我该怎么做才能解决这个问题:(
我希望在插入 EFCore 时,它可以自动为每个实体分配一个 ID,无论其 Id 是否被设置?
答: 暂无答案
评论