我想通过关系从不同的表中检索数据库中的数据,但我得到了一个错误,我不知道如何处理。
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()
方法上,但是如果我删除它,我就不能传递到另一个表。
发布于 2013-08-14 21:59:29
正如错误所述,您的解决方案是使用FirstOrDefault
。但是,如果ProductName
查询的结果为空,这将返回null
,这意味着您将从FirstOrDefault().Product.ProductsName.Name
获得一个NullReferenceException
。这可以通过在调用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();
发布于 2013-08-14 20:45:36
错误说明您应该使用FirstOrDefault()
而不是First()
不确定问题是什么
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),这将抛出一个错误
https://stackoverflow.com/questions/18232055
复制相似问题