Take the 2-minute tour ×

Is there anyway to use NHibernate in such a way that it whould only execute the query/queries once the returned object of a query/statement is used.. just like EF doest it?

For most instances with EF it wont send and execute the actual query to the database until the returned object of a linq-"statement" is used.. for instance:

var x = for e in entities.MyTable
select e;

This aint executed yet!
Which meens that Im able to mofidy the x-objects "linq-query" however I like without actualt "pulling" any data from the database:

x = x.Where(i=>i.SomeThing = someThing);

Still aint executed!


Now its executed!

But in NHibernate the query gets executed once the transaction gets closed or commited from what I have understod.. and in most cases thats done already in the repository. So you can't simply in any other place alter the query and then send it to the database. Cause the query is already sent and that whould mean that you later on only whould alter whats "displayed" from the result.

I might have gotten this al wrong so please correct me if I am wrong.

Huge thanks in advance!

share|improve this question
You cannot execute query in EF if you closed the context in the repository. So the behavior is the same. –  Ladislav Mrnka Dec 8 '11 at 16:02

1 Answer 1

You can try something like this using detached QueryOver

var query = QueryOver.Of<Customer>()
    .Where(x => x.LastName == "Smith"); // query is not executed yet


Good thing is that you can pass QueryOver objects and get it executed somewhere else.

share|improve this answer
If I understand you correct, this makes it possible to execute the query anytime in my code?..If yes, then if I whould create alot of QueryOvers all over the place, then how does NHibernate know which one to execute?..or will it simply just execute all of them.. or whould I need to return the query-object and then later on be able to simply type query.GetExecutableQueryOver(session).List(); to execute it? –  Inx Dec 8 '11 at 13:42

Your Answer


