Lambda expression to return a Person in the repository - DDD and Aspnet.Core

Asked

Viewed 120 times

1

I have a table Person who has one-to-one relationship with the tables PessoaFisica and PessoaJuridica.

inserir a descrição da imagem aqui

When I pass the id, it has to check me if nature is physical or legal and bring me the person + pessoafisica or pessoajuridica (The person can only be one of the two). How do I mount a lambda expression for this? Below, I have one that I’m trying to ride:

public Pessoa GetJoinById(int id)
{
            var pessoa = Db.Pessoa.FirstOrDefault(x => x.Id == id);
                //.Include("")
                //.Include("")
            pessoa.(x =>
            {
                if (x.PessoaNatureza == PessoaNatureza.Fisica)
                {
                    Db.Entry(x)
                        .Reference(f => f.PessoaFisica)
                        .Load();
                }
                else
                {
                    Db.Entry(x)
                        .Reference(j => j.PessoaJuridica)
                        .Load();
                }
            });

            return null;
}
  • It was I who posted this in another question but, it’s different, it’s wrong this! What is your doubt?

  • 1

    Yes, Virgilio. I think it was you... In that case, I was trying to send a list and it worked 100% I need to adapt for him to do the same, only sending only one person.... I don’t know how to lick.. Only sql....

2 answers

2


By means of that my answer, can bring a Pessoa with the reference if it is PessoaFisica or PessoaJuridica as follows:

public Pessoa GetJoinById(int id)
{
    var pessoa = Db.Pessoa.FirstOrDefault(x => x.Id == id);
    if  (pessoa != null)
    {
        if (pessoa.PessoaNatureza == PessoaNatureza.Fisica)
        {
            Db
                .Entry(pessoa)
                .Reference(f => f.PessoaFisica)
                .Load();
        }       
        else
        {
            Db
                .Entry(pessoa)
                .Reference(f => f.PessoaJuridica)
                .Load();
        }
        return pessoa;
    }   

    return null;
}
  • 1

    Thank you again Virgilio!!!

1

Don’t you have a field in the table that indicates the document? Like CPF or CNPJ?

Try to do this:

var pessoa = Db.Pessoa.Where(x => x.PessoaId == id).FirstOrDefault();
if (pessoa.Natureza == PessoaNatureza.Fisica){
    //carrega para pessoa fisica
}
else{
    //carrega para pessoa juridica
}
  • Thank you for your contribution Gabriel!!!

Browser other questions tagged

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