【问题标题】:MVC3 select int value through LINQMVC3 通过 LINQ 选择 int 值
【发布时间】:2012-04-16 16:33:59
【问题描述】:

我正在尝试从 Customer 表中获取 customerId。

但是,当我尝试制作它时,它有错误说,'无法将类型'System.Linq.Iqueryable'隐式转换为'int''

如何获取 customerId??

谢谢。

这是我的代码。

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

order.customerId = customerId;

【问题讨论】:

    标签: asp.net-mvc-3 linq


    【解决方案1】:

    您的查询可能会返回多行。您需要告诉 LINQ 您只想要第一个(或单个)结果:

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

    【讨论】:

    • 如果customerID 是唯一的,那么它应该是Single() 而不是First()
    【解决方案2】:

    当我知道应该只有一行时,我喜欢使用 .Single() 函数。

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

    如果发现多于或少于一行,这将引发异常,根据您的情况,这有时很有用。

    【讨论】:

      【解决方案3】:

      这样使用它: var customer = db.Customer.FirstOrDefault(c =>c.userName == customerName) var id = customer.Id

      Select 返回一个 IEnumerable,因此不能将其转换为 int。

      【讨论】:

        【解决方案4】:

        对于这个问题,我可以推荐的另一个建议是使用 First 或 default。

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

        order.customerId = customerId; 现在应该可以正常工作了,因为它已经知道 int

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多