Sqlexception: The INSERT statement conflicted with the FOREIGN KEY constraint

Asked

Viewed 1,013 times

0

I have a 1-n employee relationship.

I used the Entity Migrations to create the tables based on my models. I checked in the database and the tables were created with their respective PK and FK.

However, when my method . Savechangesasync(); is called, it is returned conflict error in bd with Foreign key.

This is my method:

// POST api/funcionario
[HttpPost]
public async Task<ActionResult<Funcionario>> cadastraFuncionario(Funcionario funcionario)
{
    _context.Funcionario.Add(funcionario);
    await _context.SaveChangesAsync();

    return NoContent();
}

My employee model:

public class Funcionario
{
    public int FuncionarioId { get; set; }
    public string Nome { get; set; }
    public string Cargo { get; set; }
    public Nullable<float> Salario { get; set; }
    //Foreign Key
    public int EmpresaId { get; set; }
    public Empresa Empresas { get; set; }
}

My model company:

 public class Empresa
    {
        public int EmpresaId { get; set;}
        public string Nome { get; set; }
        public string Cep { get; set; }
        public string Logradouro { get; set; }
        public string Complemento { get; set; }
        public Nullable<int> Numero { get; set; }
        public string Bairro { get; set; }
        public string Localidade { get; set; }
        public string UF { get; set; }
        public Nullable<int> Unidade { get; set; }
        public Nullable<int> IBGE { get; set; }
        public Nullable<int> GIA { get; set; }
        public string Telefone{get;set;}
        public ICollection<Funcionario> Funcionarios { get; set; }
    }

In my comic book owns a Company whose id is 1.

I try to make this request through Postman:

POST

{
    "empresaId": 1,
    "nome": "Teste",
    "cargo": "Teste",
    "salario": 10850
}

But I get:

An unhandled Exception occurred while Processing the request.

Sqlexception: The INSERT statement conflicted with the FOREIGN constraint KEY "Fk_funcio_empresa_empresaid". The conflict occurred in the "Crud" data, table "dbo. Company", column 'Empresaid'. A instruction was finalized. System.Data.Sqlclient.Sqlcommand+<>c.b__122_0(Task result)

Dbupdateexception: An error occurred while updating the Entries. See the Inner Exception for Details. Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Executeasync(Irelationalconnection Connection, Cancellationtoken cancellationToken)

  • Managed to solve?

  • @LP.Gonçalves probably yes, but it’s been so long that I can’t remember anymore

1 answer

1


I copied your classes and enabled Migrations. I did the example below and it worked. It only failed when no value is assigned to the property EmpresaId of Funcionario.

It worked out this way:

  public class CrudContext : DbContext
{
    public CrudContext() : base("DefaultConnection")
    {

    }
    public DbSet<Funcionario> Funcionarios { get; set; }

    public DbSet<Empresa> Empresas { get; set; }

}

public void Add()
    {
        try
        {
            using (CrudContext context = new CrudContext())
            {
                var empresa = new Empresa
                {
                    EmpresaId = 1,
                    Nome = "Empresa 3",
                    Bairro = "Teste",
                    Cep = "000000",
                    UF = "PR",
                    Logradouro = "Rua aaaaa",
                    Complemento = "aaaa",
                    Localidade = "CTBA",
                    GIA = 1,
                    IBGE = 1,
                    Numero = 10,
                    Telefone = "0000",
                    Unidade = 2
                };

                context.Empresas.Add(empresa);
                context.SaveChanges();

                // Deu certo
                var funcionario = new Funcionario { EmpresaId = 1, FuncionarioId = 2, Nome = "Teste", Cargo = "Teste", Salario = 10 };

                // Deu erro se nao informar o EmpresaId
                //var funcionario = new Funcionario { FuncionarioId = 3, Nome = "Teste", Cargo = "Teste", Salario = 10 };

                context.Funcionarios.Add(funcionario);
                context.SaveChangesAsync().Wait();

            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }

Browser other questions tagged

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