LINQ to Entities does not recognize the method: LastOrDefault

Entity framework/linq2sql works by converting your compiled C#/IL into SQL. It can only convert methods it knows. The error is telling you that LastOrDefault isn't one of those.

You can fix this by putting .ToList() before LastOrDefault, which takes it away from the sql-converter into vanilla C# and you get the regular working version of LastOrDefault. Or you can flip the order and use FirstOrDefault, which it can translate.


LastOrDefault() isn't supported by Linq To Entities. So it will work on a collection in memory, but not when you're attempting to query a database .

This is an efficient way to handle it:

var lastCompletedQuestion = 
_db.CompletedQuestions.Where(q => q.UserId == currentUserId)
.OrderByDescending(q => q.QuestionNumber)
.FirstOrDefault() 

                                                                         ;