How to Configure Mapping Entity Framework 1: N Using Inheritance

5

I have two classes: Pessoa and Usuario . The Usuario class inherits the properties and methods of the Pessoa class.

I'm using the Entity Framework and I believe you're doing the wrong mapping. So the problem is happening as shown below.

The rule would be: A person can be multiple users registered (seems to be wrong logic, but it is because of my need) and a user can only be linked to a person.

CodeMappingofthePersonclass

publicPessoaConfiguration(){ToTable("tblPessoa");

    HasKey(p => p.PessoaId);

    Property(p => p.DataInclusao).IsRequired();
}

User Class Mapping Code

public UsuarioConfiguration()
{
    ToTable("tblUsuario");

    HasKey(p => p.UsuarioId);

    HasRequired(p => p.Pessoa)
        .WithMany(u => u.Usuarios)
        .HasForeignKey(p => p.PessoaId);

    Property(c => c.NomeUsuario).HasColumnName("NomeUsuario")
        .HasColumnType("Varchar")
        .HasMaxLength(25)
        .IsRequired();

    Property(c => c.Senha).HasColumnName("Senha")
        .HasColumnType("Varchar")
        .HasMaxLength(25)
        .IsRequired();
}

Note: The image is specifying how the table should be in the database.

    
asked by anonymous 13.02.2017 / 15:57

1 answer

4

1: N of Pessoa with Usuario can not be inherit, unfortunately. Inheritance does not assume multiple cardinality.

The case of inheritance is something like this:

public class Usuario
{ ... }

public class Pessoa : Usuario
{ ... }

That is, Pessoa is Usuario , but a Usuario need not necessarily be Pessoa . Both are in the same relationship or collection in the database.

In your case, the Entity Framework is sure to make the keys separate because you are using multiple cardinality, and Usuarios and Pessoas are not the same thing.

If a Pessoa has multiple registered users, the correct one is:

public class Pessoa
{
    ...

    public virtual ICollection<Usuario> Usuarios { get; set; }
}

public class Usuario
{
    public int UsuarioId { get; set; }
    public int PessoaId { get; set; }

    ...

    public virtual Pessoa Pessoa { get; set; }
}
    
13.02.2017 / 16:05