转换表达式来; T,BOOL>为String [英] Converting Expression<T, bool> to String

查看:95
本文介绍了转换表达式来; T,BOOL>为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来重新在未来的某个时候动态生成的报告。长话短说,我需要一个特定的LINQ查询(每个报告不同)存储到数据库中,然后执行动态的LINQ以后查询。

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.

如:

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?

推荐答案

这可能不是最好/最有效的方法,但它< 。EM>确实的作品

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

这篇关于转换表达式来; T,BOOL&GT;为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆