gpt4 book ai didi

linq-to-entities - 如何处理错误 “method '首先只能用作最终查询操作”

转载 作者:行者123 更新时间:2023-12-03 12:11:10 25 4
gpt4 key购买 nike

我想按关系从不同表的数据库中检索数据,但是出现一个我不知道如何处理的错误。

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();

Unhandled Exception: System.NotSupportedException: The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.



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

最佳答案

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

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();

关于linq-to-entities - 如何处理错误 “method '首先只能用作最终查询操作”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18232055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com