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

后端 未结 2 1121
遇见更好的自我
遇见更好的自我 2021-02-12 11:17

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.         


        
2条回答
  •  逝去的感伤
    2021-02-12 11:44

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

提交回复
热议问题