I'm having some serious issues trying to create a table using code first. So this is what I have:
public class Pessoa
{
[Key]
public int PessoaId { get; set; }
public virtual Empresa Empresa { get; set; }
...
}
public class Empresa
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int EmpresaId { get; set; }
public virtual List<FuncionarioFree> FuncionarioFree { get; set; }
public virtual List<FuncionarioPagante> FuncionarioPagante { get; set; }
[Key,ForeignKey("Pessoa")]
public int PessoaId { get; set; }
[Required]
public virtual Pessoa Pessoa { get; set; }
...
}
public class FuncionarioPagante
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FuncionarioPaganteId { get; set; }
public int PessoaId { get; set; }
[ForeignKey("PessoaId")]
public virtual Pessoa Pessoa { get; set; }
public int EmpresaId { get; set; }
[ForeignKey("EmpresaId")]
public virtual Empresa Empresa { get; set; }
}
Now for what I need:
Pessoa
may or may not have a Empresa
(company). And Empresa
has a list of FuncionarioPagante
(employees).
Now when i try to insert a new FuncionarioPagante
:
var novoFuncionario = new FuncionarioPagante()
{
EmpresaId = empresaId,
Pessoa = pessoaUnidade.Pessoa,
PessoaId = pessoaUnidade.PessoaId
};
_contexto.FuncionarioPagante.Add(novoFuncionario);
_contexto.SaveChanges();
It is trowing this error: (Note: in this case, both Pessoa
and Empresa
already exists in the db)
"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.FuncionarioFree_dbo.Empresa_EmpresaId\". The conflict occurred in database \"...", table \"dbo.Empresa\", column 'PessoaId'.\r\nThe statement has been terminated."
EDIT: I did some more tests and it works when i try to insert a new FuncionarioPagante with a Pessoa that has a Empresa. But that doesn't make sense to me. The Pessoa that i am inserting shouldn't had to have a Empresa in order to be inserted into a list of FuncionarioPagante in an Empresa of someone else.
EDIT 2: When i insert it with Empresa it works as well, like this:
var empresa = _contexto.Empresa.Where(x => x.EmpresaId == empresaId).FirstOrDefault();
var novoFuncionario = new FuncionarioPagante()
{
EmpresaId = empresaId,
Pessoa = pessoaUnidade.Pessoa,
Empresa = empresa,
PessoaId = pessoaUnidade.PessoaId
};
But the value inserted in EmpresaId changes to the value of PessoaId of the owner of the Empresa after SaveChanges()