c# – Problema com ValueObject no Entity framework

Question:

I'm having a hard time with a mapping and would like to know if it's possible to do this:

I have a Contact class with two fields that are ValueObject of type "Phone", the fields are Phone and Mobile.

public Telefone Telefone { get; set; }
public Telefone Celular { get; set; }

I would like to do the following mapping so that Phone is mandatory and cell phone is not:

Property(x => x.Telefone.DDD)
  .HasColumnName("TelefoneDDD")
  .IsRequired();
Property(x => x.Telefone.Numero)
  .HasColumnName("Telefone")
  .IsRequired();
Property(x => x.Celular.DDD)
  .HasColumnName("CelularDDD")
  .IsOptional();
Property(x => x.Celular.Numero)
  .HasColumnName("Celular")
  .IsOptional();

When I generate the migration, it returns the following error:

Conflicting configuration settings were specified for property 'Number' on type 'TestSystem.Domain.ValueObject.Phone': IsNullable = False conflicts with IsNullable = True

Answer:

You should have a separate configuration for the Phone entity and just key in the two fields in your main entity. In one of them you leave it as Mandatory and the other does not

public class Telefone
{
    public int Codigo {get;set;}
    public int DDD {get;set;}
    public string Numero {get;set;}
}

public class Cadastro
{
    public int CodigoTelefone {get;set;}
    public Telefone Telefone {get;set;}
    public int? CodigoCelular {get;set;}
    public Telefone Celular {get;set;}
}

//Mapeamento da classe Cadastro

HasRequired(c => c.Telefone)
    .WithMany()
    .HasForeignKey(c => c.CodigoTelefone)
    .WillCascadeOnDelete(true); // Telefone é obrigatório

HasOptional(c => c.Celular)
    .WithMany()
    .HasForeignKey(c => c.CodigoCelular)
    .WillCascadeOnDelete(true); // Celular não é obrigatório
Scroll to Top