I need to convert Expression<Func<T, bool>> to string. How can I do it?
This is the predicate I'm trying to convert:
我需要将表达式
>转换为字符串。我该怎么做呢?这是我试图转换的谓词:
var prezziList = ExecQuery<Listino>(i => i.CodArt == articolo.CodArt);
I'm using the method suggested here: Converting Expression<T, bool> to String, and this is my method:
我正在使用这里建议的方法:将表达式
转换为字符串,以下是我的方法:
public List<TEntity> ExecQuery<TEntity>(Expression<Func<T, bool>> predicate)
{
string expBody = predicate.Body.ToString();
var paramName = predicate.Parameters[0].Name;
var paramTypeName = predicate.Parameters[0].Type.Name;
expBody = expBody.Replace(paramName + ".", paramTypeName + ".")
.Replace("AndAlso", "&&")
.Replace("==", "=");
SQLiteCommand sQLiteCommand = new(App.CNManager.Connection);
sQLiteCommand.CommandText = $"SELECT * FROM myTable WHERE {expBody}";
return sQLiteCommand.ExecuteQuery<TEntity>();
}
but it returns following string, which obviously is not in the correct format:
但它返回以下字符串,该字符串的格式显然不正确:
"Listino.CodArt = value(Vendo.ViewModels.DettaglioArticoliViewModel+<>c__DisplayClass184_0).articolo.CodArt"
“Listino.CodArt=value(Vendo.ViewModels.DettaglioArticoliViewModel+<>c__DisplayClass184_0).articolo.CodArt”
Where am I doing wrong?
我哪里做错了?
更多回答
Wouldn't it be better to use Entity Framework or Dappr or another ORM than this manual hack of modifying expressions?
使用实体框架或Dappr或其他ORM不是比手动修改表达式更好吗?
The title in both questions is wrong, and the source of your problems. You don't convert expressions to strings. You're asking how to convert an expression tree to a specific language, SQL. There are infinite languages that can be generated for a single expression tree. The answer is to use a visitor that understands both the expression tree and the target language and emits whatever you want in the target language.
这两个问题的标题都是错误的,也是你的问题的根源。您不能将表达式转换为字符串。您正在询问如何将表达式树转换为特定的语言,即SQL。可以为单个表达式树生成无限种语言。答案是使用既能理解表达式树又能理解目标语言的访问器,并用目标语言输出您想要的任何内容。
优秀答案推荐
As Steve Wilkes said in this post you can use AgileObjects.ReadableExpressions.
正如Steve Wilkes在这篇文章中所说的,你可以使用AgileObjects.ReadableExpressions。
After installing Package Using following command:
安装程序包后,使用以下命令:
PM> Install-Package AgileObjects.ReadableExpressions
You can use it in this way
你可以这样用它
using AgileObjects.ReadableExpressions;
string readable = myExpression.ToReadableString();
The difference between your example and that question is, your condition is a variable articolo.CodArt
, the condition in that answer is a const value.
你的例子和问题之间的区别是,你的条件是一个变量,CodArt,答案中的条件是一个常量值。
Therefore you need to use some measure to get that value, simply replace with get the stringfy value of the variable.
因此,您需要使用某种方法来获取该值,只需将其替换为获取变量的字符串值。
You need to pass the object which need to get value, in your case is articolo
, then call predicate.Compile().Invoke(articolo)
to get the value, then translate it into SQL.
您需要传递需要获取值的对象,在本例中是Articolo,然后调用Predicate.Compile().Invoke(Articolo)来获取值,然后将其转换为SQL。
更多回答
我是一名优秀的程序员,十分优秀!