2012-04-16 62 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(); 

如果多于或少于一行被发现,根据您的情况有时它是有用这会抛出异常。