Converting Expression<T, bool> to String
Asked Answered
V

1

42

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<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?

Varicocele answered 25/1, 2011 at 13:20 Comment(7)
I think you are asking Expression<Func<Product,bool>>, I have modified your question.Assumptive
This is roughly the same question as this: #218461Ironwood
Yes, that's correct, I left the func part out.Varicocele
Perhaps this will help: code.msdn.microsoft.com/exprserializationScrimmage
What is wrong with ToString() ?Countable
@leppie: ToString() apparently returns metadata from reflection, not the actual string representation of the lambda expression.Varicocele
possible duplicate of convert-an-expression-tree-to-source-code-stringBibliographer
F
51

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))
Ferrite answered 25/1, 2011 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.