Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
207 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...