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
@LP.Gonçalves probably yes, but it’s been so long that I can’t remember anymore
– veroneseComS