Entity Framework trying to insert duplicate record

Asked

Viewed 54 times

0

I am starting an application in Blazor, using Entity Framework and Mysql database.

Below I will detail the Tables, Models, Context and Method that is presenting me problem:

Tables: https://i.stack.Imgur.com/d8UMW.png

Context:

public class ContextoEtapa : Contexto
{
    public DbSet<Etapa> Etapa { get; set; }
}

Models:

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

    public string Descricao { get; set; }

    public bool Ativo { get; set; }

    public bool Finalizadora { get; set; }

    [InverseProperty("EtapaPai")]
    public virtual List<EtapaVinculada> ListaEtapaVinculada { get; set; }
}

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

    public string Descricao { get; set; }

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

    public virtual Etapa EtapaPai { get; set; }

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

    public virtual Etapa EtapaFilha { get; set; }
}

Example code that fails (Innerexception = {"Duplicate entry '2' for key 'PRIMARY'"}):

public void Adicionar()
{
    try
    {
        var etapa = new Etapa();
        var etapaVinculada = new EtapaVinculada();

        etapa.ListaEtapaVinculada = new List<EtapaVinculada>();
        etapa.Descricao = "Aprovada";

        using (var contexto = new ContextoEtapa())
        {
            etapaVinculada.EtapaPai = etapa;
            etapaVinculada.EtapaFilha = contexto.Etapa.Where(x => x.Id == 2).FirstOrDefault();
            etapaVinculada.Descricao = "Retornar para Desenvolvimento";

            etapa.ListaEtapaVinculada.Add(etapaVinculada);
        }

        using (var contexto = new ContextoEtapa())
        {
            contexto.Etapa.Add(etapa);
            contexto.SaveChanges();
        }
    }
    catch (Exception excp)
    {
        throw excp;
    }
}

Note: These are examples codes that reflect a real situation of my application. In my case I fill the step object at a given time using a context scope, and then to save in the database I use another context scope, then falling into the Duplicate record error (Innerexception = {"Duplicate entry '2' for key 'PRIMARY'"}). It seems to me that the Entity tries to insert again in the table of steps the object of the ID 2 window.
Note: If I do everything within the same context scope it works correctly.

Can someone give me a light and see where I’m going wrong, please.

1 answer

-3

  • I tried in the past, but just in case I tried again and without success. Same duplicity error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.