0
I have a problem in the relationship of entities with the Entity Framework Core v3.1.5
, Code First
I have entity Cliente
relating to the entity DadosProfissional
and my problem is, when I register a client, even though I don’t have information for professional data, it’s done Insert
in that table and I would like it to happen only when I actually had information for that entity.
The class this client:
public class Cliente
{
public Int64 ClienteId { get; set; }
public String Nome { get; set; }
public DateTime DataNascimento { get; set; }
public String Telefone { get; set; }
public string Filhos { get; set; }
public Int64? PaisId { get; set; }
public virtual Pais Pais { get; set; }
public Int64? EstadoId { get; set; }
public virtual Estado Estado { get; set; }
public Int64? CidadeId { get; set; }
public Int64? DadosProfissionalId { get; set; }
public virtual DadosProfissional DadosProfissional { get; set; }
public virtual Cidade Cidade { get; set; }
public string RG { get; set; }
public string CPF { get; set; }
public string Email { get; set; }
}
public class DadosProfissional
{
public Int64 DadosProfissionailId { get; set; }
public Int64? ProfissaoId { get; set; }
public Int64? NivelId { get; set; }
public Int64? EmpresaId { get; set;}
public Int64? PaisId { get; set; }
public Int64? EstadoId { get; set; }
public Int64? CidadeId { get; set; }
public int? SituacaoContratoId { get; set; }
public DateTime? DataInicio { get; set; }
public DateTime? DataFim { get; set; }
public decimal? Renda { get; set; }
public virtual Pais Pais { get; set; }
public virtual Estado Estado { get; set; }
public virtual Cidade Cidade { get; set; }
public virtual Profissao Profissao { get; set; }
public virtual Nivel Nivel { get; set; }
public virtual Empresa Empresa { get; set; }
public virtual SituacaoContrato SituacaoContrato { get; set; }
}
if
DadosProfissional
is null it will not insert– Ricardo Pontual
That’s exactly the behavior I was hoping for... but you’re inserting
– Ricardo Soares
If the object is null, how can you enter some value? EF can’t "invent" data, it just inserts what’s in the objects, recheck the Property, there’s something wrong. Another possibility is to "untie" the table
DadosProfissional
model when saving, something likeobjetoDeContext.Entry(DadosProfissional).State = EntityState.Detached
– Ricardo Pontual
what may be happening is that the auto-mapper, creates a new object, qndo do the mapping and so it does the Insert
– Ricardo Soares
The strategy is another, needs to create in this Entity or even better in another Class that represents this model a validation where it is obligated that all fields including the relationship are filled.
– novic