Iterate a Linq expression and convert it to a DB parameter

How can I repeat the Linq expression and convert it to a DB parameter so that I can avoid passing multiple parameters as input to the DAL method

Business Layer:  In BL, I have code like this

  database.GetProduct(a => a.ProductType == "tea" || a.Price <= 5);

In DAL, I use simple ADO.Net and want to convert the expression that I returned from BL to ADO.Net parameters

Data Access Level:

 public DataSet GetProduct(Expression<Func<Product, bool>> pred)
 {

    step 1:
          Iterate the predicate and create new sqlparameter.
    step 2:
      return database.ExecuteDataset(parameters)    
 }

How can I repeat "pred" and convert it to SQLParameter

0
source share
3 answers

, . ExpressionVisitor, node . , (, , ), NodeType .

:

static void HandlePrimitive(Expression e) {
  // TODO: Handle primitive cases (>, <, <=, !=, >=, ..)
  Console.WriteLine(e.NodeType);
}

static void Process(Expression e) {
  if (e.NodeType == ExpressionType.OrElse)
  {
    // Process left subexpression (one (in)equality) as primitive
    // and right subexpression recursively (it may be either primitive 
    // or another OrElse node.
    var be = e as BinaryExpression;
    HandlePrimitive(be.Left);
    Process(be.Right);
  }
  else HandlePrimitive(e);
}

Expression<Func<Product,bool>> f = a => a.ProductType == "tea" || a.Price <= 5;
Process(f.Body);

Process , "" ( "" ). HandlePrimitive , ||'s. These are other BinaryExpression values (e.g. Equal or LessThanEqual ). You'll need to look at their and Right`, , .. .

+1

, , , , . IQToolkit ExpressionVisitor, . , VisitMemberAccess .

+1

You do not want to follow this road. You are about to override LINQ to SQL. I can assume that you are using optional arguments:

public DataSet GetProduct(int? maxPrice = null, string type = null)
{
    //... snip ...
    if (price.HasValue) whereClause += " OR price <= " + maxPrice";
    //... snip ...
}
-1
source

Source: https://habr.com/ru/post/1789124/


All Articles