How does this NHibernate code influence the commit?

38 Views Asked by At

I ran into an issue where the following code results in an exception.

public IList<Persoon> GetPersonenWithCurrentWorkScheme(int clientId)
    {
        //SELECT N+1
        Session.QueryOver<Werkschema>()
            .Fetch(ws => ws.Labels).Eager
            .JoinQueryOver<WerkschemaHistory>(p => p.Histories)
            .JoinQueryOver<ArbeidsContract>(a => a.ArbeidsContract)
            .JoinQueryOver<Persoon>(p => p.Persoon)
            .Where(p => p.Klant.ID == clientId)
            .Future();

        var result = Session.QueryOver<Persoon>()
            .Fetch(p => p.ArbeidsContracten).Eager
            .Where(p => p.Klant.ID == clientId)
            .Future();

        return result.ToList();
    }

When I comment the first part of the method (Session.QueryOver WerkSchema...) the code runs fine. When it is not commented, the first NHibernate.Commit() that occurs throws an exception. (Something with a date-time conversion but that's not really what I'm worried about).

My question: Is the first bit of code useful? Does it do anything? The result is not stored in a variable which is used later, so to me it looks like dead code. Or is this some NHibernate dark magic which actually does something useful?

1

There are 1 best solutions below

0
Amit Joshi On

The Future is an optimization over existing API provided by NHibernate.

One of the nicest new features in NHibernate 2.1 is the Future() and FutureValue() functions. They essentially function as a way to defer query execution to a later date, at which point NHibernate will have more information about what the application is supposed to do, and optimize for it accordingly. This build on an existing feature of NHibernate, Multi Queries, but does so in a way that is easy to use and almost seamless.

This will execute multiple queries in single round trip to database. If it is not possible to get all the needed data in single round trip, multiple calls will be executed as expected; but it still helps in many cases.

The database call is triggered when first round trip is requested.

In your case, first round trip is requested by calling result.ToList(), which also including your first part of code.

As you suspect, output of first part; though retrieved is never being used. So in my view, that part can be safely commented. But, this is based on code you post in question only.

It may be the case that the data loaded while this call is saving round-trips in other part of code. But in that case, code should be optimized and should be moved to proper location.