Generic Query Method
Asked Answered
P

1

6

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();
    }
}
Push answered 9/10, 2013 at 19:13 Comment(2)
Don´t you need a Expression<Func<T, bool>> criteria instead of a Predicate<T> criteria in your generic method?Marutani
Thanks Jehof, that put me on the right track...Push
M
2

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();
    }
}
Marutani answered 9/10, 2013 at 19:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.