How to map a relationship using EF Core

Asked

Viewed 125 times

2

My Pessoa entity may also be an Employee entity. I have the need that, whenever I register a Person, I must inform the Employee who registered it, being Person as Primary Key and Personal Key as Foreign Key. NOTE: I only mentioned the Id fields so the table doesn’t get big. I need to do the mapping using EF Core, but I don’t know how to do it. Someone knows how to help me?

public class Pessoa : Entity
{
    public int PessoaId  { get; private set; }
    public int PessoaFuncionarioId  { get; private set; }
}


public class PessoaMap : IEntityTypeConfiguration<Pessoa>
{
    public void Configure(EntityTypeBuilder<Pessoa> builder)
    {
        builder.ToTable("Pessoa");

        builder.HasKey(p => p.Id);

        builder.Property(p => p.Id)
            .HasColumnName("PessoaId")
            .HasColumnType("integer")
            .HasDefaultValueSql("nextval('\"PessoaIdSeq\"')")
            .IsRequired();

            //????????????????????


    }
}

inserir a descrição da imagem aqui

  • just the character of curiosity, how would you add the first person if you were not yet going to have any employee who is also a person?

  • First I add the employee and then the other people :)

  • Yes, I saw there later in the drawing that can be null, but in your class the first thing I would need is to change from int to int nullable, I am working out an answer here, I already command

1 answer

1


as commented, the first thing to be done is to render Personal

public class Pessoa : Entity
{
    public int PessoaId  { get; private set; }
    public int? PessoaFuncionarioId  { get; private set; }
    public virtual Pessoa PessoaFuncionario  { get; private set; }
}

in Mapping is already simpler, just reference a configuration one for many

public class PessoaMap : IEntityTypeConfiguration<Pessoa>
{
    public void Configure(EntityTypeBuilder<Pessoa> builder)
    {
        builder.ToTable("Pessoa");

        builder.HasKey(p => p.Id);

        builder.Property(p => p.Id)
            .HasColumnName("PessoaId")
            .HasColumnType("integer")
            .HasDefaultValueSql("nextval('\"PessoaIdSeq\"')")
            .IsRequired();

            //????????????????????

       builder.HasOne(_ => _.PessoaFuncionario)
            .WithMany()
            .HasForeignKey(t => t.PessoaFuncionarioId)
            .IsRequired(false);

    }
}
  • Thank you @Lucas Miranda! :)

Browser other questions tagged

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