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 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.
This query allows the user or a procedure to specify the column names and row conditions just before running the query.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With