Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate 3.0: No FirstOrDefault() with QueryOver?

I am playing with FluentNHibernate and NH 3.0, using the LINQ provider and the new QueryOver syntax.

Now with QueryOver I want to get an item (called result) with a timestamp value as close as possible to a given value, but not greater:

 Result precedingOrMatchingResult = Session.QueryOver<Result>().         Where(r => r.TimeStamp < timeStamp).         OrderBy(r => r.TimeStamp).Desc.                         FirstOrDefault(); //get the preceding or matching result, if there is any 

Now, Intellisense tells me that there is no such thing as a FirstOrDefault() method. I could, of course, enumerate my ordered query, and then use LINQ to get my item. But this would load all items into memory first.

Is there an alternative to FirstOrDefault(), or have I understood something completely wrong?

like image 414
Marcel Avatar asked Dec 29 '10 13:12

Marcel


2 Answers

I have now found out that I could use the Take() extension method on the IQueryOver instance, and only the enumerate to a list, like so:

Result precedingOrMatchingResult = Session.QueryOver<Result>().         Where(r => r.TimeStamp < timeStamp).         OrderBy(r => r.TimeStamp).Desc.            Take(1).List(). //enumerate only on element of the sequence!         FirstOrDefault(); //get the preceding or matching result, if there is any 
like image 199
Marcel Avatar answered Sep 19 '22 16:09

Marcel


Result precedingOrMatchingResult = Session.QueryOver<Result>()                                           .Where(r => r.TimeStamp < timeStamp)                                           .OrderBy(r => r.TimeStamp).Desc                                           .SingleOrDefault(); 
like image 41
RRR Avatar answered Sep 22 '22 16:09

RRR