Sunday, June 1, 2014

SELECT BOTTOM with Linq

Added Last/LastOrDefault functionality in our custom ORM, so we can now do things in idiomatic way, e.g., getting the last country alphabetically.

Non-idiomatic, we are getting the last country, yet we are using FirstOrDefault:
var lastCountry = countryDao.Context.OrderByDescending(x => x.CountryName).FirstOrDefault();

Idiomatic way to get the last row:
var lastCountry = countryDao.Context.OrderBy(x => x.CountryName).LastOrDefault();


Both of the codes above resolves to SELECT TOP ORDER BY DESC, as there's no SELECT BOTTOM in SQL:
SELECT TOP 1 c.CountryId, c.CountryName, c.Population
FROM Countries c
ORDER BY c.CountryName DESC


I naturally assumed NHibernate and Entity Framework supports Last/LastOrDefault, just tried them now, but they haven't supported it yet

No comments:

Post a Comment