سؤال

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();
    }
}
هل كانت مفيدة؟

المحلول

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();
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top