我想按关系从数据库中的不同表中检索数据,但出现错误,我不知道如何处理。
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()
方法,但如果我删除它,我就无法传递到另一个表。
正如错误所述,您的解决方案是使用FirstOrDefault
。然而,这将返回null
如果结果ProductName
查询为空,这意味着您会得到NullReferenceException
from 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)