2011-10-16 69 views
2

我有這個查詢。Linq的字符(字符串)編碼數字比較

levelnumber = (from b in bv.baLevels 
       where b.ba_Level_Code == ("0" + SqlFunctions.StringConvert((double)cl.Level_Num.Value)) && b.isActive == 1 
       select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault(), 

我的問題是b.ba_Level_Code是字符串。

cl.Level_Num is Int。

baLevels表我有這個ba_Level_code值有008

但CL是BaCodeLibrary表這個cl.Level_Num有8

,如果我做的查詢與硬編碼值

levelnumber = (from b in bv.baLevels 
       where b.ba_Level_Code == "008" && b.isActive == 1 
       select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault(), 

如何顯示008? cl.Level_Num我越來越有8我需要將該值更改爲008

感謝

回答

1

你可以使用string.Format指定你的`cl.Level_Num」轉換爲一個字符串的最小數量數字:

string.Format("{0:D3}", cl.Level_Num.Value) // would ouput "008" value 8 

這樣:

levelnumber = (from b in bv.baLevels 
       where b.ba_Level_Code == string.Format("{0:D3}", cl.Level_Num.Value) && b.isActive == 1 
       select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault() 
+0

感謝Jeffora,但我在表中的一些其他級別數有046023056 ....等等..我想我那個時候會遇到問題。 – user957178

+0

我收到此錯誤.LINQ實體無法識別方法'System.String格式(System.String,System.Object)'方法,並且此方法無法轉換爲存儲表達式。 – user957178

+0

@ user957178看起來像你必須將第二個參數轉換爲一個類型。 – Hogan

2

我看不到一個很好的方式在LINQ這樣做是爲了Enties。假設您無法修改ba_Level_Code列的數據類型,我認爲您最好的選擇是將持久computed column添加到該表中,對其進行索引並在查詢中使用該列。

例如,如果你定義的列

ba_Level_Code_Int as (case when isnumeric(ba_Level_Code)= 1 then cast(ba_Level_Code as int) end) persisted 

那麼你的LINQ查詢可能是

levelnumber = (from b in bv.baLevels 
       where b.ba_Level_Code_Int == cl.Level_Num.Value && b.isActive == 1 
       select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault();