In a Linq Expression body how to use the value of a variable instead of a reference to it?

前端 未结 1 1883
生来不讨喜
生来不讨喜 2021-01-15 19:06

Here is my code:

IQueryable data = dc.TradeCard.Include(\"Address\").Include(\"Vehicle\");

string orderNumber = \"ORD_NR_2\";
Expressio         


        
相关标签:
1条回答
  • 2021-01-15 19:46

    The code in this blog post provides a way to evaluate all sections of an expression into values, in all of the places that it can be done.

    First it walks through the expression tree from the bottom up, indicating which objects don't have an parameter objects as any of their children. Then it walk through the tree from the top down, evaluating all expressions to a value that don't have a parameter in them.

    We can also create an additional method specifically for an expression representing a Func with one parameter so that you don't need to do the cast when you call it:

    public static Expression<Func<TIn, TOut>> Simplify<TIn, TOut>(
        this Expression<Func<TIn, TOut>> expression)
    {
        return (Expression<Func<TIn, TOut>>)Evaluator.PartialEval(expression);
    }
    

    This allows you to write:

    string orderNumber = "ORD_NR_2";
    Expression<Func<DAL.TradeCard, bool>> whereClause = a => a.orderNumber == orderNumber;
    string foo = whereClause.Simplify().ToString();
    //foo will be "{a => (a.orderNumber == "ORD_NR_2")}"
    
    0 讨论(0)
提交回复
热议问题