Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout for NHibernate LINQ statement

I am using Fluent NHibernate for my ORM. In doing so I am trying to use the NHibernate LINQ syntax to fetch a set of data with the power of LINQ. The code I have works and executes correctly with the exception being that a timeout is thrown if it takes longer than roughly 30 seconds to run. The question I have is how do I extend the default 30 second timeout for LINQ statements via NHibernate?

I have already seen the posts here, here, and here but the first two refer to setting the DataContext's Timeout property, which does not apply here, and the third refers to setting the timeout in XML, which also does not apply because I am using Fluent NHibernate to generate the XML on the fly. Not only that but the post is 2 years old and Fluent NHibernate has changed since.

With the ICriteria objects and even HQL I can specify the timeout, however that is not the goal here. I would like to know how to set that same timeout and use LINQ.

Example code:

    using (var session = SessionFactory.OpenSession())
    using (var transaction = session.BeginTransaction())
    {
        var query = (from mem in session.Query<Member>()
                     select mem);
        query = query.Where({where statement});
        int start = (currentPage - 1) * max);
        if (start > 0)
            query = query.Skip(start).Take(max);
        else
            query = query.Take(max);

        var list = query.ToList();
        transaction.Commit();
        return list;
    }

This code (where statement does not matter) works for all purposes except where a timeout occurs.

Any help is appreciated. Thanks in advance!

like image 544
Brandon Wenzel Avatar asked Oct 16 '12 16:10

Brandon Wenzel


2 Answers

I ended up setting the command timeout for the Configuration for Fluent NHibernate. The downside to this is that it sets the timeout for ALL of my data access calls and not just the one.

Example code:

.ExposeConfiguration(c => c.SetProperty("command_timeout", (TimeSpan.FromMinutes(10).TotalSeconds).ToString()))

I found this suggestion from this website.

like image 184
Brandon Wenzel Avatar answered Oct 25 '22 20:10

Brandon Wenzel


Nhibernate has extended the IQueryable and added a few methods https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate/Linq/LinqExtensionMethods.cs

var query = (from c in Session.Query<Puppy>()).Timeout(12);

or

var query = (from c in Session.Query<Puppy>());

query.Timeout(456);
like image 9
Kingpin2k Avatar answered Oct 25 '22 20:10

Kingpin2k