C# 实体框架抛出;已添加具有相同密钥的项";

C# 实体框架抛出;已添加具有相同密钥的项";,c#,entity-framework,mariadb,entity-framework-core,C#,Entity Framework,Mariadb,Entity Framework Core,我得到一个例外: 已添加具有相同密钥的项。钥匙:p2072 这是在将实体添加到DbContext后调用SaveChanges的时候 奇怪的是,它说的是“Key:p2072”,但它与我的实体的任何键都不匹配 主键配置如下: modelBuilder.Entity<RequestEntity>().HasKey(e => new { e.Nif, e.Especialidad, e.Cuerpo }); public class RequestEntity { publi

我得到一个例外:

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

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

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

主键配置如下:

modelBuilder.Entity<RequestEntity>().HasKey(e => new { e.Nif, e.Especialidad, e.Cuerpo });
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、Iligoas和Estado是枚举。请注意,与其他实体没有任何关系,只有基元类型

我很难调试它,因为要添加+23000个实体,而且似乎没有任何重复项

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

编辑 这是堆栈跟踪:

在 System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(对象 在System.Collections.Generic.Dictionary
2.TryInsert(TKey,
TValue值,InsertionBehavior)位于
System.Collections.Generic.Dictionary
2.Add(TKey,TValue)
在 Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.CreateStoreCommand() 在 Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection 连接)在 Microsoft.EntityFrameworkCore.Update.Internal.MySqlBatchExecutor.Execute(IEnumerable
1
commandBatches,IRelationalConnection)位于
Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList
1 参赛作品)在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 (保存)在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(布尔值 可接受的改变(成功) Microsoft.EntityFrameworkCore.DbContext.SaveChanges(布尔值 可接受的改变(成功) Microsoft.EntityFrameworkCore.DbContext.SaveChanges()位于 Plugin.Clm.Importer.Importer.SaveNewResults(ImportResults)

编辑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();
有趣的是,
replices
没有任何元素(0个元素)。发生了什么事?

(代表问题作者发布)


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

根据我的经验,“已添加具有相同密钥的项”应该在附加过程中抛出,而不是.SaveChanges()。然而,这可能是他们改变了核心。为了调试,您可以尝试将所有条目分割成小的块,比如100个条目,然后进行调试,我高度怀疑重复的条目。为了便于检查,您还可以检查表达式条目.GroupBy(e=>new{e.Nif,e.specialidad,e.Cuerpo});我们能看到异常堆栈跟踪吗?@DevilSuichiro请查找更新的问题。很可能是OK中的错误,我刚刚发现了问题。这是一只虫子。我正在使用Pomelo Mysql EF提供程序。更新到最新版本修复了该问题。谢谢你的建议!