实体框架-关键字"PRIMARY"的重复条目"1" [英] Entity Framework - Duplicate entry '1' for key 'PRIMARY'"

查看:91
本文介绍了实体框架-关键字"PRIMARY"的重复条目"1"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MySql DB和Entity Framework,当我尝试插入包含子数据列表的数据时,我收到此错误:InnerException = {键"PRIMARY"的重复条目'1'"}

Using MySql DB and Entity Framework, when im trying insert a data that contais a lists of child data i recive this error: InnerException = {"Duplicate entry '1' for key 'PRIMARY'"}

这是我的桌子的图像: https://i.stack.imgur.com/bAnVy.png

Here is a image of my tables: https://i.stack.imgur.com/bAnVy.png

public class Etapa 
{
    public int Id { get; set; }

    public string Descricao { get; set; }

    [Column("ativo", TypeName = "bit")]
    public bool Ativo { get; set; }

    [Column("finalizadora", TypeName = "bit")]
    public bool Finalizadora { get; set; }

    public List<EtapaVinculada> ListaEtapaVinculada { get; set; }
}


[Table("etapa_vinculada")]
public class EtapaVinculada 
{
    public int Id { get; set; }

    [Column("id_etapa_pai")]
    public int EtapaPaiId { get; set; }

    public Etapa EtapaPai { get; set; }

    [Column("id_etapa_filha")]
    public int EtapaFilhaId { get; set; }

    public Etapa EtapaFilha { get; set; }

    public string Descricao { get; set; }
}

Etapa的上下文在这里:

Etapa's contexts is here:

public class ContextoEtapa : Contexto
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Etapa>().HasMany(x => x.ListaEtapaVinculada).WithOne(y => y.EtapaPai).HasForeignKey(x => x.EtapaPaiId);
    }

    public async Task Adicionar(Etapa registro)
    {
        await AddAsync(registro);
        await SaveChangesAsync();
    }
}

手动填充数据库中的表,当我调试上下文时,我可以看到我的Etapa对象已填充,并且属性ListEtapaVinculada也正确地填充了.

Filling manually the tables in DB, when i debug my context i can see my Etapa object is filled and the property ListEtapaVinculada is filled too, correctly.

当要使用Add方法将填充有其EtapaVinculada列表的Etapa对象插入数据库时​​,就会发生问题.在我看来,我做了一些错误的映射,因为它给人一种印象,即Entity试图连续插入2倍Etapa记录,从而导致重复键错误.

The problem happens when the Etapa object filled with its list of EtapaVinculada is going to be inserted into the database using the Add method. It seems to me that I did some wrong mapping, because it gives the impression that Entity tries to insert 2x the Etapa record in a row, falling into the duplicate key error.

自动递增正在工作.如果我尝试保存这样的对象:

The auto increment is working. If i try to save a object like this:

 {
        Etapa etapa = new Etapa();
        etapa.Descricao = "test";
        etapa.Ativo = true;
        etapa.Finalizadora = true;
        etapa.ListaEtapaVinculada = new List<EtapaVinculada>(); // Without itens

        using (var context = new ContextoEtapa())
        {
            await context.Etapa.AddAsync(etapa);
            await context.SaveChangesAsync();
        }
    }

但是,如果我做这样的事情:

But, if i do something like this:

 {
        Etapa etapaFilha = null;

        using (var context = new ContextEtapa())
        {
            etapaFilha = await context.Etapa.Where(x => x.Id == 666).First();
        }

        Etapa etapa = new Etapa();
        etapa.Descricao = "test";
        etapa.Ativo = true;
        etapa.Finalizadora = true;
        etapa.ListaEtapaVinculada = new List<EtapaVinculada>();

        EtapaVinculada etapaVinculada = new EtapaVinculada();
        etapaVinculada.EtapaPaiId = etapa.Id;
        etapaVinculada.EtapaPai = etapa;
        etapaVinculada.EtapaFilhaId = etapaFilha.Id;
        etapaVinculada.EtapaFilha = etapaFilha;

        etapa.listaEtapaVinculada.Add(etapaVinculada);

        using (var context = new ContextoEtapa())
        {
            await context.Etapa.AddAsync(etapa);
            await context.SaveChangesAsync();
        }
    }

现在我得到了重复密钥的错误.在我看来,EF尝试插入2个Etapa对象,正确的方法是插入Etapa,然后插入ListaEtapaVinculada的所有项目.

Now i got the erros of duplicate Key. Its seems to me that EF is trying to insert 2x Etapa object, when the correct is insert Etapa, then insert all itens of ListaEtapaVinculada.

推荐答案

我认为问题在于,当尝试同时分配对象的实例和ID时,请尝试对以下代码行进行注释:

I think the problem is when trying to assign an instance of the object and an id at the same time, try commenting on the following line of code:

 {
    Etapa etapaFilha = null;

    using (var context = new ContextEtapa())
    {
        etapaFilha = await context.Etapa.Where(x => x.Id == 666).First();
    }

    Etapa etapa = new Etapa();
    etapa.Descricao = "test";
    etapa.Ativo = true;
    etapa.Finalizadora = true;
    etapa.ListaEtapaVinculada = new List<EtapaVinculada>();

    EtapaVinculada etapaVinculada = new EtapaVinculada();
    // etapaVinculada.EtapaPaiId = etapa.Id; // this is asigned when asign to collection and savechanges

    // etapaVinculada.EtapaPai = etapa;

    etapaVinculada.EtapaFilhaId = etapaFilha.Id; // 

    // etapaVinculada.EtapaFilha = etapaFilha; this is duplicate

    etapa.listaEtapaVinculada.Add(etapaVinculada);

    using (var context = new ContextoEtapa())
    {
        await context.Etapa.AddAsync(etapa);
        await context.SaveChangesAsync();
    }
}

这篇关于实体框架-关键字"PRIMARY"的重复条目"1"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆