本文介绍了如何处理错误“方法'First'只能用作最终查询操作".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to retrieve data from the database in different tables by relation, but I get an error that I don't know how to handle.

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

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

The problem is with the .First() method, but if I remove it I can't pass to another table.

推荐答案

由于出现错误,您的解决方案是使用FirstOrDefault.但是,如果ProductName查询的结果为空,这将返回null,这意味着您将从FirstOrDefault().Product.ProductsName.Name中获得NullReferenceException.这可以通过在调用FirstOrDefault():

Your solution, as the error states - is to use FirstOrDefault. This, however, will return null if the result of ProductName query is empty, meaning you'd get a NullReferenceException from FirstOrDefault().Product.ProductsName.Name. This is solved by moving the property transform earlier in the query, before the call to 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();

这篇关于如何处理错误“方法'First'只能用作最终查询操作".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:21