Query using LINQ and Generics C#

Asked

Viewed 177 times

1

I’m having difficulty to perform a query with LINQ using Generics.

Something like:

from x in session.Query<T>() " ??? "

My method takes two strings as parameters, Column and valueBack.

public virtual object PesquisePorColunaValor(string colunaDeBusca, string valorDeBusca)
    {
         // TODO Query em LINQ
    }
  • You want to do a dynamic search according to the value passed by the right parameter?

  • 2

    ??? Tell us what your question is. Explain what is happening, what you want to get at, give context to what you are doing. There’s a lot of nonsense played.

  • @Pedro Explain your question better, I believe that what Voce wants is to create a method that runs a dynamic query to be searched in a Collections, if that is it, I find it difficult to do this using the column name as String.

  • This Jéferson, is a method that serves for all entities. The search is according to the column name and the value sent by string.

  • from x in Session. Query<T>() select x returns all T records

  • @Julioborges The problem is that I can’t escape this pattern of the method. Because there is already a lot working with it.

  • I will implement without the use of Generics for now. I appreciate the attention of all.

Show 2 more comments

1 answer

3

I believe you can not do this dynamic search using a String to get the column that will be searched.

The ideal is to use the resources Expression, Func and Generics.

public virtual IQueryable<T> Pesquisar(Expression<Func<T, bool>> predicate)
{
    IQueryable<T> lquerySentenca = session.Query<T>().Where(predicate);
    return lquerySentenca;
}

public virtual List<T> PesquisarComList(Expression<Func<T, bool>> predicate)
{
    return Pesquisar(predicate).ToList();
}

public void Executando()
{
    List<Aluno> lst = Pesquisar<Aluno>(o => o.Nome == "Jose").ToList();
    List<Aluno> lst2 = PesquisarComList<Aluno>(o => o.Nome == "Jose").ToList();
}
  • Okay, I’ll run a test on this implementation and I’ll get back to you.

Browser other questions tagged

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