2012-03-03 101 views
1

我的代碼:無法隱式轉換類型 'System.Collections.Generic.IEnumerable <dynamic>' 到 '廉政'

int key = 0; 
      //get primary key of inserted row 
      key = db.Query("SELECT max(event_id) FROM event where title=" + cevent.title + "AND description=" + cevent.description + "AND event_start=" + cevent.start + "AND event_end=" + cevent.end); 

錯誤消息:

無法隱式轉換類型 「System.Collections中。 Generic.IEnumerable'到'int'

我正在使用C#,WebMatrix和SQL Server。 WebMatrix中。如果我嘗試運行的ExecuteScalar代替查詢,我得到

「WebMatrix.Data.Database」不包含一個定義 「的ExecuteScalar」

有誰知道我能做些什麼來解決我的代碼?

+0

也許'db.Query'返回一個IEnumerable而不是int ??錯誤信息很清楚。 – vulkanino 2012-03-03 17:58:19

回答

1

這聽起來像你想要Database.QueryValue來代替。

// No need to declare it beforehand... 
int key = (int) db.QueryValue(...); 

而且在你前面的問題,你絕對應該被嵌入SQL中的查詢參數值。

Database.QueryValue被記錄爲:

執行返回單個標量值作爲結果的SQL查詢。

......這聽起來恰到好處。這是值得瀏覽文檔 - 他們不是很詳細,但它至少會告訴你什麼是可用的。

+0

不用擔心,我的工作將會得到解決!非常感謝回覆: – 2012-03-03 17:59:25

0

你的key是整數,你不能投一個整數System.Collections.Generic.IEnumerable,作爲消息報答。

如果肯定有結果只有一個,寫的是這樣的:

key = (int)db.Query("SELECT max(event_id) FROM event where title=" + 
          cevent.title + "AND description=" + 
          cevent.description + "AND event_start=" + 
          cevent.start + "AND event_end=" + cevent.end). 
          FirstOrDefault(); 

應該足夠給你。

+0

如果您確定只有一個結果,那麼'SingleOrDefault()'比'FirstOrDefault()'更合適。 – BACON 2012-03-03 20:13:08

相關問題