Modify generic method to merge information into classes

Asked

Viewed 88 times

0

I’m a first-time sailor with the Entityframework and I’m working with a class USUARIO who inherits from PESSOA.

There are other classes like PESSOATIPO, PESSOAFISICA, PESSOAJURIDICA, etc., the problem is that when I carry my DataGridView, Entityframework cannot separate the data from each table and position the fields correctly within the lines. See how PESSOAFISICA was should be presented the fields NOMECOMPLETO, APELIDO And DATANASCIMENTO.

Tabela

This is because I have a generic function that returns me all this. I wonder if it gives to implement/amend the function below to pass some kind of select (Lambda) to return me columns in the order I want, and so the DataGridview be loaded correctly and the charging has a good performance?

Example:

Usuario.Select(x=> x.USuarioId, 
               x.PessoaFisica.NomeCompleto, 
               x.PessoaFisica.Apelido, 
               x.PessoaFisica.DataNascimento).

I mean, something like.

public List<TEntity> GetAll(Expression<Func<TEntity, bool>> Predicate)
{
    var query = Context.Set<TEntity>().Where(Predicate).ToList();
    return query;
}

1 answer

0


Yes, there is a way to bring you a list with type created at runtime (can also be created a class representing this new data model), create a method with the code below, where TResult is a new data type that will be created on output and can assign the new list in the DataGridView

public List<TResult> GetAll<TResult>(Expression<Func<TEntity, bool>> predicate, 
                                     Expression<Func<TEntity, TResult>> select)
{
    var query = Context.Set<TEntity>()
                       .Where(predicate)
                       .Select(select) 
                       .ToList();
    return query;
}

In the method call would be:

.GetAll(x => x.UsuarioId == 1, s = new {
        s.UsuarioId, ... //e continua colocando os dados da relação e precisa
});

Observing: I believe I should implement the interface to propagate in the implementing classes.

References:

  • Virgilio, I have a question about creating this Tresult class... In my generic class, all functions return a Tentity, but with Tresult I don’t know how to implement... You would have as an example?

  • @Jalberromano in this case I put in the answer you don’t need to do anything just call the GetAll and pass the two expressions as is in the example, he takes care to bring this TResult according to your selection (Select) of data. You yourself have done just above a Select is very similar in the second setting of this function that is in the answer

Browser other questions tagged

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