Brian Watson
Brian Watson

Reputation: 31

Not supported exception in LINQ Lambda

I have this code and it gives me this following error "LINQ to Entities does not recognize the method"

var AuxiliarValue = _context.company.LastOrDefault(x => x.StartValue.HasValue && (x.StartValue.Value < InicialValue));

InicialValue is Double

But when I put a ToList(), it works

var AuxiliarValue = _context.company.ToList().LastOrDefault(x => x.StartValue.HasValue && (x.StartValue.Value < InicialValue)); 

Can anyone explain to me why it works with ToList()?

Upvotes: 0

Views: 724

Answers (2)

Servy
Servy

Reputation: 203830

It works when you add ToList because the query is no longer being translated into SQL and executed by the database. Instead, the entire table of data is returned from the database to your application, a List is built to hold that data, and then the operation is performed using LINQ to Objects.

You probably don't want to do that; you probably want to adjust the way that you query the data such that it can be translated into SQL and run against the database.

Upvotes: 2

Habib
Habib

Reputation: 223332

LastOrDefault is not supported with LINQ to Entities. You can use OrderByDescending and then use FirstOrDefault

var AuxiliarValue = _context.company
                        .OrderByDescending(r=> yourFieldtoOrder)
                        .FirstOrDefault(x => x.StartValue.HasValue && (x.StartValue.Value < InicialValue));

The reason it works with ToList is that ToList will iterate all the results and bring them in memory, so the LastOrDefault is executed on an in-memory collection, rather than at the database end.

Upvotes: 4

Related Questions