What is the best way to read entity properties in "Include" with similar names?

Asked

Viewed 23 times

-1

I have the following consultation:

            var recs = (from p in _db.Fichas
                    .Include(c => c.Tipo01)
                    .Include(c => c.Tipo02)
                    .Include(c => c.Tipo03)
                    .Include(c => c.Pessoa01)
                    .Include(c => c.Pessoa02)
                    .Include(c => c.Pessoa03)
                    .AsNoTracking()
                    where p.Id == 100
                    select p).FirstOrDefault();

Based on the above query, I am getting and reading (I believe mistakenly) the values of the following properties:

        var nome1 = recs.Pessoa01 != null ? recs.Pessoa01.Nome : null;
        var nome2 = recs.Pessoa02 != null ? recs.Pessoa02.Nome : null;
        var nome3 = recs.Pessoa03 != null ? recs.Pessoa03.Nome : null;
        var tip1 = recs.Tipo01 != null ? recs.Tipo01.ModeloA : null;
        var tip2 = recs.Tipo02 != null ? recs.Tipo02.ModeloA : null;

Some colleague could help me and show me a more decent way to perform this task?

Hug Hugo

1 answer

0

From your question, I can’t be sure what you’re up to... But if the goal is to remove these ternary conditions and considering that your code is prepared to work with these null values. You can write these statements in simpler and more readable ways.

    var nome1 = recs?.Pessoa01?.Nome;
    var nome2 = recs?.Pessoa02?.Nome;
    var nome3 = recs?.Pessoa03?.Nome;
    var tip1 = recs?.Tipo01?.ModeloA;
    var tip2 = recs?.Tipo02?.ModeloA;

I also recommend that you re-evaluate the name of your properties, variables and objects... Pessoa01, nome1, Tipo01 and tip1 don’t make any semantic sense. And if your domain is structured that way, you’d better review your project from the bottom.

  • Good morning, Leandro. Thank you very much for your feedback. I am giving maintenance on third party system. In fact, to save development lines, I thought of something as a loop to read the properties and entities. For example, instead of having to get the "Name" of the entities "Personal,01, Personal," etc.".

  • Something like that: rec. Person(i+1). Name Got it?

Browser other questions tagged

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