0

Could you explain why LastOrDefault doesn't works where FirstOrDefault do the job without any problem. It seems these 2 methods are not the same:

Ont his example from LinqPad:

 var varone = Guid.Parse("bbb3d139-fbec-430c-9574-02f3412c95df");
 Price.Where(y => y.Id == varone && y.ApplicationDate.Value <= new DateTime(2016,06,01))
                .OrderByDescending(y => y.ApplicationDate.Value)
                .LastOrDefault().Dump();

I get a

NotSupportedException: LINQ to Entities does not recognize the method 'Nppg.Core.BusinessModels.BeperEntities.Price LastOrDefaultPrice' method, and this method cannot be translated into a store expression.

But no problem if I replace LastOrDefault by FirstOrDefault

 var varone = Guid.Parse("bbb3d139-fbec-430c-9574-02f3412c95df");
 Price.Where(y => y.Id == varone && y.ApplicationDate.Value <= new DateTime(2016,06,01))
                .OrderByDescending(y => y.ApplicationDate.Value)
                .FirstOrDefault().Dump();
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • 2
    What exactly is so hard to unserstand? While you can easily translate `First` to valid SQL (for example `limit 1` on postgres or `where rownum = 1` on oracle), there´s no equivalent for the last element in sql. – MakePeaceGreatAgain Dec 08 '16 at 08:34
  • Simply put, whoever wrote the LINQ to Entities framework have not implemented support for `LastOrDefault`. Additionally, you can reverse the ordering and simply use `FirstOrDefault` instead, so it shouldn't really be needed. – Lasse V. Karlsen Dec 08 '16 at 08:34
  • `LastOrDefault` has to scan the *entire cursor* (and so can be *very expensive*), that's why it should be avoided; change `OrderByDescending` to `OrderBy` and put `FirstOrDefault()` – Dmitry Bychenko Dec 08 '16 at 08:35
  • @DmitryBychenko This is true, however there are many functions that´ll also scan the entire collection, so this allone won´t be a valid reason. – MakePeaceGreatAgain Dec 08 '16 at 08:36
  • @HimBromBeere Can be the answer but you can also expect it is also easily to translate the 'Last' to a valid SQL. Why not? Read my question like this. – Bastien Vandamme Dec 08 '16 at 08:36
  • No, bvecause there is *no* sql-equivalent, whilst for `First`there *is* one in most dialects. – MakePeaceGreatAgain Dec 08 '16 at 08:37
  • 1
    @Rawling Thank you for the link to the duplicate question. – Bastien Vandamme Dec 08 '16 at 08:39

0 Answers0