Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Query Method

Trying to reduce repetition in my code by making a generic GET method. I am using OrmLite and its SQLExpressionVisitor update... The goal is to pass in a lambda. I have seen a few other posts that I hoped would help but so far, no go... It is clear the problem is how I am trying to get the criteria evaluated in the ev.Where statement, but the solution is escaping me...

Thanks in advance... -Lenny

public IQueryable<T> Get<T>(Predicate<T> criteria)
{
  using (IDbConnection db = dbConnectionFactory.OpenDbConnection())
    {
     SqlExpressionVisitor<T> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
     ev.Where(x => criteria.Invoke(x))
     return db.Select(ev).AsQueryable();
    }
 }

This is the error I get... variable 'x' of type 'TW.Api.Models.CostCenter' referenced from scope '', but it is not defined

Here is an example of code that works but is not generic....

public IQueryable<CostCenter> Get(Identity user)
{
    using (IDbConnection db = dbConnectionFactory.OpenDbConnection())
      {
        SqlExpressionVisitor<CostCenter> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<CostCenter>();
        ev.Where(x => x.OrgId == user.OrgId);
        ev.Where(x => x.VisibilityStockpointId == user.StockpointId);``
        return db.Select(ev).AsQueryable();
  }
}

This is the model I referenced above...

[Alias("CostCenterDetail")]
public class CostCenter
{
    public Guid Id { get; set; }
    public Guid StockpointId { get; set; }
    public virtual Guid? VisibilityStockpointId { get; set; }
    public string Description { get; set; }
    public string Number { get; set; }
    public string OrgId { get; set; }
}

for all reading this, here is the final code...

    public IQueryable<T> Get<T>(Expression<Func<T, bool>> criteria)
{
    using (IDbConnection db = dbConnectionFactory.OpenDbConnection())
    {
        return db.Select(criteria).AsQueryable();
    }
}
like image 795
Lenny Avatar asked Oct 09 '13 19:10

Lenny


People also ask

What is generic query?

You build generic queries by using the building blocks in the Queries tool. You do not need to know SQL to create generic queries. The building blocks that you select specify the criteria to use to retrieve data, including table names, column names, and a set of conditions.

What is generic query in SQL?

This query allows the user or a procedure to specify the column names and row conditions just before running the query.


1 Answers

You need to use an Expression<Func<T, bool>> instead of a Predicate<T> as parameter for your generic method.

public IQueryable<T> Get<T>(Expression<Func<T, bool>> criteria) {
    using (IDbConnection db = dbConnectionFactory.OpenDbConnection())
    {
        return db.Select(criteria).AsQueryable();
    }
}
like image 84
Jehof Avatar answered Sep 22 '22 14:09

Jehof