【问题标题】:Entity Framework throws "An item with the same key has already been added"实体框架抛出“已添加具有相同键的项目”
【发布时间】:2018-06-29 13:40:41
【问题描述】:

我遇到了这个异常:

已添加具有相同密钥的项目。键:p2072

这是在将实体添加到DbContext 后调用SaveChanges

奇怪的是它说 "Key: p2072",但它与我实体的任何键都不匹配。

主键配置如下:

modelBuilder.Entity<RequestEntity>().HasKey(e => new { e.Nif, e.Especialidad, e.Cuerpo });

地点:

  • Nif 是string
  • 特别是int
  • Cuerpo是Enum

您可以看到实体的完整定义。如下:

public class RequestEntity
{
    public string Nif { get; set; }
    public Provincias Provincias { get; set; }
    public Cuerpo Cuerpo { get; set; }
    public int Especialidad { get; set; }
    public Estado Estado { get; set; }
    public Idiomas Idiomas { get; set; }
    public int Orden { get; set; }
}

Provicias、Cuerpo、Idiomas 和 Estado 是枚举。请注意,与其他实体没有任何关系,只有原始类型。

我很难对此进行调试,因为要添加 +23,000 个实体,而且似乎没有任何重复。

此外,它显示的键 (p2072) 没有意义。键中唯一的字符串是 Nif,但没有匹配的 Nif。

编辑

这是堆栈跟踪:

在 System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(对象 键)在 System.Collections.Generic.Dictionary2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Collections.Generic.Dictionary2.Add(TKey 键,TValue 值)
在 Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.CreateStoreCommand() 在 Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection 连接)在 Microsoft.EntityFrameworkCore.Update.Internal.MySqlBatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList1 条目)在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 条目保存)在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(布尔 接受AllChangesOnSuccess)在 Microsoft.EntityFrameworkCore.DbContext.SaveChanges(布尔值 接受AllChangesOnSuccess)在 Microsoft.EntityFrameworkCore.DbContext.SaveChanges() 在 Plugin.Clm.Importer.Importer.SaveNewResults(ImportResult 结果)

编辑 2

就在SaveChanges 之前,我放了这行:

        var duplicates = requestEntities.GroupBy(e=>new{e.Nif, e.Especialidad, e.Cuerpo}).Select(x=>new{x.Key, Count = x.Count()})
            .Where(x => x.Count > 1)
            .ToList();

有趣的是duplicates 什么都没有(0 个元素)。怎么回事?

【问题讨论】:

  • 根据我的经验,“已添加具有相同密钥的项目”应该在附加期间抛出,而不是 .SaveChanges()。但是,可能是他们在核心上改变了这一点。为了调试,您可以尝试将所有条目分成小块,如 100 个条目并像这样调试,我高度怀疑重复。为了方便检查,您还可以检查表达式 entries.GroupBy(e=>new{e.Nif, e.Especialidad, e.Cuerpo}).Select(x=>new{x.Key, x.Count()} );
  • 我们能看到异常堆栈跟踪吗?
  • @DevilSuichiro 请寻找更新后的问题。
  • 很可能是MySQL EF Core Database Provider中的错误
  • 好的,我刚刚发现了问题。这是一个错误。我正在使用 Pomelo Mysql EF 提供程序。更新到最新版本解决了这个问题。感谢您的建议!

标签: c# entity-framework mariadb entity-framework-core


【解决方案1】:

(代表问题作者发布).

这恰好是我正在使用的 Pomelo EF MySQL 提供程序中的一个错误!更新到最新版本即可解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2017-04-15
    相关资源
    最近更新 更多