首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何处理错误“方法'First‘只能用作最终查询操作”

如何处理错误“方法'First‘只能用作最终查询操作”
EN

Stack Overflow用户
提问于 2013-08-14 20:41:07
回答 2查看 14.6K关注 0票数 22

我想通过关系从不同的表中检索数据库中的数据,但我得到了一个错误,我不知道如何处理。

代码语言:javascript
复制
int customer_id = int.Parse(this.comboBoxnamecustomer.SelectedValue.ToString());

a = (from c in db.Invoices where c.CustomerID == customer_id select new { 
        customerName = c.Customer.Name,
        ProductName = c.InvoiceItems
            .Where(x => x.InvoiceId == c.InvoiceId)
            .First().Product.ProductsName.Name
    }).ToList();

未处理的异常: System.NotSupportedException:方法'First‘只能用作最终查询操作。请考虑在此实例中改用'FirstOrDefault‘方法。

问题出在.First()方法上,但是如果我删除它,我就不能传递到另一个表。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-14 21:59:29

正如错误所述,您的解决方案是使用FirstOrDefault。但是,如果ProductName查询的结果为空,这将返回null,这意味着您将从FirstOrDefault().Product.ProductsName.Name获得一个NullReferenceException。这可以通过在调用FirstOrDefault()之前在查询中较早地移动属性转换来解决

代码语言:javascript
复制
a = (from c in db.Invoices where c.CustomerID == customer_id select new { 
     customerName=c.Customer.Name,
     ProductName=c.InvoiceItems.Where(x=> x.InvoiceId==c.InvoiceId)
                               .Select(i => i.Product.ProductsName.Name)
                               .FirstOrDefault()
}).ToList();
票数 32
EN

Stack Overflow用户

发布于 2013-08-14 20:45:36

错误说明您应该使用FirstOrDefault()而不是First()

不确定问题是什么

代码语言:javascript
复制
int customer_id = int.Parse(this.comboBoxnamecustomer.SelectedValue.ToString());

a = (from c in db.Invoices where c.CustomerID == customer_id select new { 
         customerName=c.Customer.Name,ProductName=c.InvoiceItems.Where(x=> x.InvoiceId==c.InvoiceId).FirstOrDefault().Product.ProductsName.Name
        }).ToList();
        dataGridViekryar.DataSource = a;

当然,如果查询中没有任何项(NullReferenceException),这将抛出一个错误

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18232055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档