Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle error "method 'First' can only be used as a final query operation"

Tags:

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

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.

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

like image 651
Dana Ali Avatar asked Aug 14 '13 12:08

Dana Ali


2 Answers

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();
like image 91
RoadieRich Avatar answered Sep 23 '22 01:09

RoadieRich


The error is stating that you should use FirstOrDefault() instead of First()

Not sure what the question is

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;

Of course this will throw an error if there isn't any items from your query (NullReferenceException)

like image 26
Sayse Avatar answered Sep 22 '22 01:09

Sayse