EF Core Relationships one-to-Many-to-Many Fluentapi

Asked

Viewed 298 times

2

Good afternoon, I’d like to take a relationship question from Entity Core. I have a table person and the person has a position (Manager, supervisor, responsible, etc..)

public class Pessoa
{
    public int PessoaId { get; set; }
    public string Nome { get; set; }
    public int CargoId { get; set; }
    public virtual Cargo { get; set; }
}
public class Cargo
{
    public int CargoId { get; set; }
    public string Nome { get; set; }
    public virtual ICollection Pessoas { get; private set; }
}

So far I have no doubt.

Now let’s assume that I have a Room table and this room has a Manager, a Supervisor and a Guardian, who are People. How would the relationship look ?

Thus:

public class Sala
{
    public int SalaId { get; set; }
    public string Nome { get; set; }
    public int ResponsavelId { get; set; }
    public virtual Pessoa Responsavel {get; set; }
    public int SupervisorId { get; set; }
    public virtual Pessoa Supervisor {get; set; }
    public int GerenteId { get; set; }
    public virtual Pessoa Gerente {get; set; }

}

And would alter Pessoa

public class Pessoa
{
    public int PessoaId { get; set; }
    public string Nome { get; set; }
    public int CargoId { get; set; }
    public virtual Cargo { get; set; }

    public virtual ICollection Salas { get; private set; }
}

And would create the relationship in of each field in the Fluent API with the Rooms property or

public class Pessoa
{
    public int PessoaId { get; set; }
    public string Nome { get; set; }
    public int CargoId { get; set; }
    public virtual Cargo { get; set; }

    public virtual ICollection SalaResponsavel { get; private set; }
    public virtual ICollection SalaSupervisor { get; private set; }
    public virtual ICollection SalaGerente { get; private set; }
}

2 answers

1

This way you’re doing it, it would look like this:

 public virtual Sala SalaResponsavel { get; private set; }
 public virtual Sala SalaSupervisor { get; private set; }
 public virtual Sala SalaGerente { get; private set; }

But I think it gets a little messy, I think I’d make another table containing

Sala
Pessoa
Cargo

So the relationship would be n-n

I’m by cell phone now, the night I try to complement more the answer

  • I think I understand your idea. But what happens is that people already have a position regardless of whether they are associated with the room or not. That is why today I have the Person table and the Charge. In the rooms I have to link people who have certain Positions. Maybe I can create a table to make an n-n kind Personal but it would not be explicit the positions I have to associate.

  • I believe https://stackoverflow.com/questions/42745465/ef-core-many-to-many-relationship-on-a-class solve my problem. Tomorrow I’ll test and return.

0

Browser other questions tagged

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