我使用System.Linq.Dynamic來提供一些數據庫源(SQL服務器)的動態查詢,並且它運行得非常好,但現在我遇到了一些問題。我需要能夠取兩個數字列並將它們格式化爲單個字符串。本質上是這樣做的是,我正在做這樣的事情(注意,這不完全是我所做的事情,因爲整個事情是動態的,而實際上傳遞給Select
的字符串是動態構建的):如何使用動態linq將兩列轉換爲單個字符串列?
var mystuff = data.Select("year, qtr, string.Format(\"{0}Q{1}\",year,qtr) as yearQtr");
出人意料的是,System.Linq.Dynamic
不實際出現解釋這是我想要的,但不幸的是,它拋出一個System.ArgumentException
錯誤:
Expression of type 'System.Int16' cannot be used for parameter of type 'System.Object'
of method 'System.String Format(System.String, System.Object, System.Object)'
我認爲的問題是,它不是拳擊fact.year
(這是System.Int16
類型)會自動像通常使用string.Format
時那樣。那麼有沒有辦法告訴它框year
和qtr
?
我試圖簡單地鑄造object
,但是,這並不工作:
var mystuff = data.Select("year, qtr, string.Format(\"{0}Q{1}\",(object)year,(object)qtr) as yearQtr");
An exception of type 'System.Linq.Dynamic.ParseException' occurred in JobsEQ.Web.dll but was not handled in user code
Additional information: '.' or '(' expected
顯然動態LINQ不明白鑄造。
更新:它發生在我剛ToString()
他們:
var mystuff = data.Select("year, qtr, string.Format(\"{0}Q{1}\",year.ToString(),qtr.ToString()) as yearQtr");
但現在我得到一個不同的異常(System.NotSupportedException
)這讓我覺得我得走錯了路:
LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object)' method, and this method cannot be translated into a store expression.
那麼還有另一種方法可以將這兩列轉換爲一個字符串列嗎?
看起來像string.format方法綁定在sql中執行。你有沒有嘗試'年+'Q'+ QTR'(就像你在SQL中做的那樣)而不是string.format? – Reniuz 2014-09-24 14:19:56
@Reniuz:這實際上給了我相同的裝箱問題:''System.Int16'類型的表達式不能用於方法'System.String Concat(System.Object,System.Object)'類型的'System.Object' ''並添加'ToString'導致類似的'LINQ to Entities不能識別該方法'System.String.Concat(...'' – 2014-09-24 14:29:41
然後最後一件事我會嘗試的是與[SqlFunction.StringConvert] (http://msdn.microsoft.com/en-us/library/dd466276(v=vs.110).aspx)但仍期待類似的字符串到對象錯誤:) – Reniuz 2014-09-24 14:55:39