18

I'm getting an error when using the following code

var v1 = from P in db1.QuranWordsNews where P.Aye == perId select P;
var vv = v1.LastOrDefault(); // The error occurs here

The message:

LINQ to Entities does not recognize the method 'TashihQuran.QuranWordsNew LastOrDefaultQuranWordsNew' method, and this method cannot be translated into a store expression.

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
mj-gholami
  • 883
  • 1
  • 6
  • 19
  • possible duplicate of [Error, method not supported by LINQ to Entities](http://stackoverflow.com/questions/2170141/error-method-not-supported-by-linq-to-entities) – sloth Jul 10 '12 at 10:33
  • Possible duplicate of [LINQ To Entities does not recognize the method Last. Really?](http://stackoverflow.com/questions/7293639/linq-to-entities-does-not-recognize-the-method-last-really) – Tot Zam Mar 02 '17 at 16:35

2 Answers2

45

Maybe the better answer is here :

var vv = v1.OrderByDescending(rec => rec.Id).FirstOrDefault();

Fetch all records from database to use just the last record is not good.

Ali Foroughi
  • 4,540
  • 7
  • 42
  • 66
  • 1
    Agree with your statement, but in OP's case, doesn't v1 already contain "all records" from database? – gitsitgo Apr 24 '14 at 16:36
35

I guess you're still working in IQueriable. Try instead

var vv = v1.ToList().LastOrDefault();

or, more elegant

var vv = v1.AsEnumerable().LastOrDefault();
phipsgabler
  • 20,535
  • 4
  • 40
  • 60