5

I'm using NHibernate future queries in an MVC 3 web application, and trying to keep all my database access happening in my controllers, and not in my views. The site is a catalog of Resources (descriptive blurbs), which have a many-to-many collection of Grades, and a many-to-many collection of Topics. Users select one or more grades, and one or more topics, and then get a list of matching resources.

In order to populate the search form, I'm using future queries to get all the grades and topics:

    public Domain.SearchFormData GetSearchFormData()
    {
        // Get all grades and all topics using a multiquery.

        IEnumerable<Grade> grades = Session.QueryOver<Grade>()
            .Future();

        IEnumerable<Topic> topics = Session.QueryOver<Topic>()
            .Future();

        var result = new SearchFormData();
        result.Grades = grades;
        result.Topics = topics;
        return result;
    }

This is very simple and works fine, and returns a SearchFormData, which is a simple DTO. This query is executed in the controller, and the result doesn't need any further processing, so it's passed right into the view for rendering as lists of checkboxes.

But because of the lazy execution of future queries, the database access isn't triggered until the view starts iterating the lists. This is considered by some (like NHibernate Profiler) to be a no-no, and they say that by the time the view starts rendering, all of the database access should be done. The principal reason is that it's easy to have a hidden SELECT N+1 going on if you don't.

Here that doesn't apply; both grade and topic are simple objects without collections. I don't mind too much that the view will trigger database access. But it's making me look for a clean, clear, way to trigger all the future queries. One way to do it is to access the results, like by copying the IEnumerable into a list. But that's not really something I need to do; I just want to execute the queued up queries.

I think it makes sense for the trigger to happen outside the query above. I might need other data to render the full page view, and I might be using other future queries to get it. For example, the home page might also show the five most popular resources and the total number of resources. Then the controller would be invoking multiple methods to accumulate what it needs for the view, and it would be most efficient to execute all of them at once. Of course one way to do that is to expand my GetSearchFormData into GetAllHomePageData and return a DTO with fields for everything on the home page. But I use the search form all over, not just on the home page. So I'd be losing some nice modularity that way.

Carl Raymond
  • 4,429
  • 2
  • 25
  • 39
  • 1
    I just tried doing a flush, but that doesn't seem to trigger future queries. – Carl Raymond Jun 13 '11 at 16:57
  • is there a specific reason you want to use Future()?I think Future() has a very specific use and is an optimization. You are telling NHibernate to optimize your queries if multiple Future()s exist and can be combined somehow. Sounds to me like you are doing optimization in a place where it might not be necessary. I am not an expert in the matter though. – Can Gencer Jun 24 '11 at 20:59
  • 1
    @CanGencer, this is exactly the type of scenario where `Future` is useful. He has multiple queries that he is executing. If possible, they should be batched together in a single round-trip to the database. That's what `Future` is for. – Daniel Schilling Mar 21 '13 at 21:42

3 Answers3

2

The following approach needs a bit of polish, but here it is anyway. I hope it's useful to somebody. I may come back later and clean it up.

For LINQ, HQL, and SQL Query futures, use:

public static void ExecuteFutureQueries(this ISession session)
{
    var sessionImpl = (ISessionImplementor) session;
    var dummy = sessionImpl.FutureQueryBatch.Results;
}

For QueryOver and ICriteria futures, use:

public static void ExecuteFutureCriteria(this ISession session)
{
    var sessionImpl = (ISessionImplementor) session;
    var dummy = sessionImpl.FutureCriteriaBatch.Results;
}

Be careful, though. Calling this method when there are no future queries of that type will result in an exception being thrown.

Daniel Schilling
  • 4,829
  • 28
  • 60
1

Daniel Schilling's answer was good, but the NH's API has changed a bit since that time. Property .Results is no longer available on that future batchers.

For the NHibernate 5.0 it should look more-or-less like this:

var eng = (NHibernate.Engine.ISessionImplementor)sess;
await eng.FutureCriteriaBatch.GetEnumerator<object>().GetEnumerableAsync();
await eng.FutureQueryBatch.GetEnumerator<object>().GetEnumerableAsync();

Instead of GetEnumerator, GetFutureValue may be used too.
If you can't use await, you can use task.Result to do a blocking wait, or you can use existing synchronous versions of GetEnumerableAsync/GetValueAsync.

Also, Daniel's warning still apply: both FutureCriteriaBatch and FutureQueryBatch throw when you try doing that and they are empty.

Unfortunatelly in NH5.0 there is no way of check if they are empty, so the only options are:

  • try-catch-ignore
  • use reflection to check FutureCriteriaBatch.queries.Count
  • add a dummy future query to ensure there is at least one of them
quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
1

I think best "solution" to this is not tu use IEnumerable in your view model classes at all - why not use simple arrays? This will force you to fully populate your models in controller and you won't loose the Linq functionality etc.

Second problem is you use your domain entities (Grade, Topic) in your SearchFormData directly - you should use DTOs instead. You mention that SearchFormData is DTO, but that's not fully true, because it references your domain entities.

So SearchFormData should look something like this:

public class SearchFormData
{
  public GradeDTO[] Grades { get; set; }
  public TopicDTO[] Topics { get; set; }
}

Your true problem is design-related problem, not NHibernate Futures problem IMO.

Buthrakaur
  • 1,821
  • 3
  • 23
  • 35
  • I have come around to the view that this is the way to do it. But I will keep @Daniel Schilling's method in my back pocket just in case. – Carl Raymond Mar 22 '13 at 20:37