我需要将表达式
var prezziList = ExecQuery<Listino>(i => i.CodArt == articolo.CodArt);
我正在使用这里建议的方法:Converting Expression
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>();
}
但它返回以下字符串,这显然格式不正确:
“Listino.CodArt = 值(Vendo.ViewModels.DettaglioArticoliViewModel+<>c__DisplayClass184_0).articolo.CodArt”
我哪里做错了?
您的示例与该问题之间的区别在于,您的条件是一个变量
articolo.CodArt
,该答案中的条件是一个常量值。
因此您需要使用一些措施来获取该值,只需替换为获取变量的 stringfy 值即可。
你需要传递需要获取值的对象,在你的例子中是
articolo
,然后调用predicate.Compile().Invoke(articolo)
来获取值,然后将其翻译成SQL。
正如Steve Wilkes在这篇文章中所说,你可以使用AgileObjects.ReadableExpressions。
使用以下代码安装包后:
PM> Install-Package AgileObjects.ReadableExpressions
你可以这样使用
using AgileObjects.ReadableExpressions;
string readable = myExpression.ToReadableString();