簡體   English   中英

Linq表達式小數包含方法

[英]Linq Expression Decimal Contains method

我有一個實質上將網格過濾器轉換為動態linq表達式的類。 網格包含一個簡單的搜索,該搜索從用戶處獲取單個輸入,我想創建一個contains語句,可用作通用搜索。 但是,我似乎找不到一種創建表達式的方法,該表達式可以采用十進制類型並創建包含(如)sql查詢。

我嘗試過的東西,但無濟於事。

明確定義為string ,我的意圖是我可以使用typeof(string)的'Contains'方法。 但是,它失敗b / c,因為它知道其十進制類型而不是字符串。 Instance property 'Total' is not defined for type 'System.String'

var parm = Expression.Parameter(typeof(string), "param");
var exp = Expression.Property(parm, filter.PropertyName);
return Expression.Call(exp, containsMethod, constant);

為十進制創建我自己的方法 ..似乎無法實現這種思路,因為LINQ無法通過該方法生成查詢。 LINQ只能使用已知的本機方法,這聽起來正確嗎?

Expression callExpr = Expression.Call(
typeof (decimal), "Contains", new[] {member.Type}, constant, param);

public static bool Contains(this decimal obj, string value)
{
   String _this = obj.ToString();
   return _this.Contains(value);
}

最終它應該生成以下sql

where total like '%43%'

和總數是十進制的數據類型

我嘗試了其他幾種方法,但效果不好,不勝感激。

我不確定您在那做什么,但請允許我為您翻譯這些行:

var parm = Expression.Parameter(typeof(string), "param");
var exp = Expression.Property(parm, filter.PropertyName);
return Expression.Call(exp, containsMethod, constant);

轉換為Linq會是這樣的:

x => x.Name.Contains("something") // something is the constant and for example Name is coming from filter.PropertyName

上面的語句將引發錯誤,因為x是字符串類型的參數,而字符串沒有Name屬性。

您的第二個陳述也是錯誤的:

Expression callExpr = Expression.Call(
typeof (decimal), "Contains", new[] {member.Type}, constant, param);

public static bool Contains(this decimal obj, string value)
{
   String _this = obj.ToString();
   return _this.Contains(value);
}

翻譯后看起來像這樣:

Contains("something", x);  // x is param and something is constant

認為“某物”應為十進制類型,因為Contains定義為第一個參數為十進制,第二個參數為字符串。

順便說一句,如果您要查找十進制以外的字符串,則可以使用Expression.Convert(..)。

有很多Expression的例子。在互聯網上轉換,只需問一下Google。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM