Trying to reduce repetition in my code by creating a generic GET method. I use OrmLite and its update SQLExpressionVisitor ... The goal is to pass to lambda. I saw several other posts that I hoped would help, but not yet. Itβs clear that the problem is how I try to get the criteria evaluated in the ev.Where proposal, but the solution eludes 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 ... a variable 'x' of type 'TW.Api.Models.CostCenter' referring to the scope '' but not defined
Here is an example of code that works, but is not general.
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 everyone 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(); } }
source share