c# – EF 6, Mapping with Fluent Api in Inherited Classes

Question:

I'm training class mapping for the Entity Framework using the Fluent API and I have some questions.

The first is as follows: Mapping a foreign key with attributes would look like this:

public int EmpresaId {get; set;}
[ForeignKey("EmpresaId")]
public Empresa Empresa {get; set;}

With the Fluent API it would be like this:

HasRequired(p => p.Empresa).WithMany().HasForeignKey(p => p.EmpresaId);

Is that correct? What I don't understand is this WithMany() since it's a simple foreign key binding and not an ICollection<> , for example. So why give WithMany() ?

The other question would be, how would the mapping with the Fluent API of these classes be, since two inherit from the first?

public class Pessoa
{
    public int Id {get; set;}
    public string Nome {get; set;}
}

public class PessoaFisica : Pessoa
{
    public string CPF {get; set;}
}

public class PessoaJuridica : Pessoa
{
    public string CNPJ {get; set;}
}

Answer:

withMany

WithMany() is used to specify a Many relationship. What's really weird is that you're using WithMany() with no arguments. WithMany() is for you to specify the inverse relationship.

For example, if that code snippet refers to a person, the correct mapping would be like this:

HasRequired(p => p.Empresa)
    .WithMany(e => e.Pessoas)
    .HasForeignKey(p => p.EmpresaId);

Person Class

A Pessoa in theory can only be Physical or Legal, right? The correct thing would be to do it like this:

public abstract class Pessoa
{
    public int Id {get; set;}
    public string Nome {get; set;}
}

public class PessoaFisica : Pessoa
{
    public string CPF {get; set;}
}

public class PessoaJuridica : Pessoa
{
    public string CNPJ {get; set;}
}

Na Fluent API:

modelBuilder.Entity<PessoaFisica>()
    .HasKey(pf => pf.Id);
modelBuilder.Entity<PessoaFisica>()
    .Property(pf => pf.Nome)
    .HasMaxLength(70)
    .IsRequired();
modelBuilder.Entity<PessoaJuridica>()
    .HasKey(pj => pj.Id);
modelBuilder.Entity<PessoaJuridica>()
    .Property(pj => pj.Nome)
    .HasMaxLength(70)
    .IsRequired();
Scroll to Top