How to configure Entity Framework Mapping 1:N using inheritance

Asked

Viewed 239 times

5

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

I am using the Entity Framework and I believe is doing the mapping wrong. That’s why the problem is happening as the image below.

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

inserir a descrição da imagem aqui

Code Class mapping Person

public PessoaConfiguration()
{
    ToTable("tblPessoa");

    HasKey(p => p.PessoaId);

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

Code User Class Mapping

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();
}

Obs.: The image is specifying how the table should look in the database.

  • yes the Entity framework plays the same primary key name of the table that represents the base class in all tables that represent derived classes. But I think this is giving error in my application: System.Data.Entity.Infrastructure.Dbupdateexception. No innerexcepition this way: The INSERT instruction conflicted with the FOREIGN KEY restriction "Fk_dbo.Cellula_dbo.Supervisor_supervisor". The conflict occurred in the database "repositorioEF.DB", table "dbo.Supervisor", column 'Id'. r in the instruction was finalized.

1 answer

4


1:n of Pessoa with Usuario cannot be inheritance, unfortunately. Inheritance does not mean multiple cardinality.

The inheritance case is something like this:

public class Usuario
{ ... }

public class Pessoa : Usuario
{ ... }

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

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

If a Pessoa has several registered users, the correct 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; }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.