2013-02-12 33 views
1

我有一個Int64字段,我想在我的EF動態Linq查詢中進行轉換。 這是因爲我想使用包含函數來檢查Int64是否包含一定數量的數字。 所以我用的是SqlFunctions.StringConvert像SqlFunctions.StringConvert和Dynamic linq

SqlFunctions.StringConvert(MyField).Contains("2012") 

動態庫提出了一個ParseException:「StringConvert」不存在任何可用的方法是在類型「SqlFunctions」。

我在動態庫而改變這個數組所以SqlFunctions將被定義:

static readonly Type[] predefinedTypes = { 
     typeof(Object), 
     ... 
     typeof(Math), 
     typeof(Convert), 
     typeof(EntityFunctions), 
     typeof(SqlFunctions) 
    }; 

奇怪的是:我還添加了EntityFunctions,而且做工精細,爲例:

EntityFunctions.TruncateTime(LastCommentDate) = @0 

UPDATE :Int64不支持的SqlFunctions:

public static string StringConvert(decimal? number); 
public static string StringConvert(double? number); 
public static string StringConvert(decimal? number, int? length); 
public static string StringConvert(double? number, int? length); 
public static string StringConvert(decimal? number, int? length, int? decimalArg); 
public static string StringConvert(double? number, int? length, int? decimalArg); 

回答

1

這是我做了什麼,以獲得SqlFu nctions.StringConvert使用EF動態Linq查詢擴展名在我的項目中工作。

下面是我嘗試去工作的代碼行,當我遇到同樣的問題時,你有但我的「屬性」是Int32而不是Int64。

query.Where("SqlFunctions.StringConvert(Property).Contains(\"12\")"); 

我添加以下代碼行至CompareConversions方法

if (s == typeof (Int32) && t1 == typeof (Decimal?)) return 1; 

我猜,你想添加像下面這樣的一線得到你的代碼工作

if (s == typeof (Int64) && t1 == typeof (Decimal?)) return 1; 

我知道這看起來像一個黑客,它是,但問題是圖書館不能選擇哪種方法

public static string StringConvert(decimal? number); 
public static string StringConvert(double? number); 

是更好的,所以我強迫它的手(和任何其他方法具有相同的簽名)通過使Int32轉換爲表達式的十進制,或在您的情況下Int64到十進制轉換。

下面是引用完成的方法

private static int CompareConversions(Type s, Type t1, Type t2) 
    { 
     if (t1 == t2) return 0; 
     if (s == t1) return 1; 
     if (s == t2) return -1; 
     bool t1t2 = IsCompatibleWith(t1, t2); 
     bool t2t1 = IsCompatibleWith(t2, t1); 
     if (t1t2 && !t2t1) return 1; 
     if (t2t1 && !t1t2) return -1; 
     if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) return 1; 
     if (IsSignedIntegralType(t2) && IsUnsignedIntegralType(t1)) return -1; 
     // HACK: SqlFunctions.StringConvert - Force it to think the Decimal Signature 
     // is better than the double for Int32 
     if (s == typeof (Int32) && t1 == typeof (Decimal?)) return 1; 
     return 0; 
    } 

希望這有助於...

0

,我認爲它會更容易先投它加倍(或十進制),因爲他們做here然後做轉換(你可以有一個可能的溢出,因爲這些浮點類型不能處理與Int64相同數量的值)

query.Where("SqlFunctions.StringConvert((double)Property).Contains(\"12\")"); 
+0

動態LINQ是否識別'SqlFunctions'? – hakuna1811 2017-10-04 06:51:38