2012-04-16 31 views
0

我試圖從Customer表中獲取customerId。MVC3通過LINQ選擇int值

然而,當我儘量做到,它錯誤說「無法隱式轉換類型‘System.Linq.Iqueryable’到'廉政」

我怎樣才能得到客戶ID?

謝謝。

這裏是我的編碼。

int customerId = from a in db.Customer 
          where a.userName == customerName 
          select a.customerId; 
          //it has error in here. 

order.customerId = customerId; 

回答

3

有可能您的查詢可能會返回多行。你需要告訴LINQ,你只需要第一個(或單)結果:

int customerId = (from a in db.Customer 
        where a.userName == customerName 
        select a.customerId).First(); 
+0

如果'customerID'是唯一比它應該是'單()'而不是'首先()' – MarcinJuraszek 2012-04-16 16:39:18

+0

非常感謝!伴侶 – wholee1 2012-04-16 16:39:59

0

使用這種方式: VAR的客戶= db.Customer.FirstOrDefault(C => c.userName ==客戶名稱) VAR ID = customer.Id

選擇返回一個IEnumerable,所以你不能把它轉換爲int。

0

還有一個建議,我可以推薦這個問題是使用第一個或默認。

var customerId = (from a in db.Customer 
          where a.userName == customerName 
          select a.customerId).FirstOrDefault(); 

order.customerId = customerId;這個現在應該可以正常工作,因爲它已經知道它詮釋

1

我喜歡使用。單()函數時,我知道應該只有一行。

int customerId = (from a in db.Customer 
        where a.userName == customerName 
        select a.customerId).Single(); 

如果多於或少於一行被發現,根據您的情況有時它是有用這會拋出異常。