[英]Convert an expression tree for a c# query expression
我在通過表達式樹轉換此查詢時遇到問題:
WageConstIn => Convert.ToString(WageConstIn.Serialno).StartsWith("2800")
這是我的表達樹:
var searchTextExp = LinqExpression.Constant("2800");
var parameterExp = LinqExpression.Parameter(typeof(WageConstInEntity), "WageConstIn");
var propertyExp = LinqExpression.Property(parameterExp, "Serialno");
var convertExpr = LinqExpression.Parameter(typeof(Convert), "Convert");
var toStringExp = LinqExpression.Call(convertExpr, "ToString", new[] { typeof(decimal) }, new[] { propertyExp });
var startsWithExp = LinqExpression.Call(toStringExp, "StartsWith", null, new[] { searchTextExp });
我收到以下錯誤:
“類型'System.Convert'上的任何方法'ToString'與提供的參數都不兼容”
Convert.ToString方法(十進制)是靜態的 ( Convert Class是靜態類)並且沒有任何泛型類型參數 。
使用Expression.Call方法(類型,字符串,類型[],表達式[]) :
通過調用適當的工廠方法,創建一個
MethodCallExpression
,該方法代表對static
方法的調用(在Visual Basic中為Shared
)。
例:
var toString = Expression.Call(typeof(Convert), "ToString", null, propertyExp);
(還請注意,Convert.ToString不是通用的,因此應為typeArguments
參數提供null
。)
這是一個LLBLGEN問題,我已經使用FunctionMapping解決了它,如下所示:
public class FunctionMappings : FunctionMappingStore
{
public FunctionMappings()
: base()
{
FunctionMapping mapping = new FunctionMapping(typeof(Functions), "Like", 2, "{0} LIKE {1}");
this.Add(mapping);
}
}
public class Functions
{
public static bool Like(string field, string value)
{
return true;
}
public static bool Like(decimal field, string value)
{
return true;
}
}
然后,我繼續按以下方式調用創建linq表達式:
ConstantExpression searchTextExp = Expression.Constant(string.Format("{0}%", searchText));
ParameterExpression parameterExp = Expression.Parameter(typeof(ViewWageConstInEntity), "WageConstIn");
MemberExpression propertyExp = Expression.Property(parameterExp, searchField);
MethodCallExpression likeExpr = null;
if (propertyExp.Type == typeof(decimal))
{
likeExpr = LinqExpression.Call(
typeof(Functions).GetMethod("Like", new[] { typeof(decimal), typeof(string) }),
propertyExp, searchTextExp);
}
else if (propertyExp.Type == typeof(string))
{
likeExpr = Expression.Call(
typeof(Functions).GetMethod("Like", new[] { typeof(string), typeof(string) }),
propertyExp, searchTextExp);
}
這將在數據庫中生成適當的SQL,如下所示:
WHERE ([Serialno] LIKE 'SearchText%')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.