Converting Expression to String

2019-01-17 03:39发布

问题:

I need a way to recreate dynamically generated reports at some point in the future. Long story short, I need to store a specific linq query (different for each report) into database and then execute the query with dynamic Linq later on.

This is all good, but I can't find a way to convert expression to string.

As in:

Expression<Func<Product, bool>> exp = (x) => (x.Id > 5 && x.Warranty != false);

should become:

"Product.Id > 5 && Product.Warranty != false"

Is there a way to do that?

回答1:

This may not be the best/most efficient method, but it does work.

Expression<Func<Product, bool>> exp = (x) => (x.Id > 5 && x.Warranty != false);

string expBody = ((LambdaExpression)exp).Body.ToString(); 
// Gives: ((x.Id > 5) AndAlso (x.Warranty != False))

var paramName = exp.Parameters[0].Name;
var paramTypeName = exp.Parameters[0].Type.Name;

// You could easily add "OrElse" and others...
expBody = expBody.Replace(paramName + ".", paramTypeName + ".")
                 .Replace("AndAlso", "&&");


Console.WriteLine(expBody);
// Output: ((Product.Id > 5) && (Product.Warranty != False))