Search code examples
nhibernatefluent-nhibernate

How to turn off locking in Fluent NHibernate?


I am running into the problem when I am importing data to a large table, the entire website goes down until the import is finished. this can take up to 3 hours for the insert/update process to finish. Also, if for some reason an exception is thrown the tables remain locked indefinitely until the application pool is restarted.

I looked into what was happening. Apparently the tables touched are locked until this process is finished. If this was direct SQL queries, I would add "with (NOLOCK)" to the query to solve the problem. However, I can't figure out how to tell Fluent NHibernate to add that to the queries it generates.

Also, is there a way when building the Session Factory that I can put in a setting to turn on "with (NOLOCK)" by default into all the queries?

Thanks in advance.


Solution

  • When you open your session or stateless session, begin a transaction with IsolationLevel.ReadUncomitted. This is the equivalent of specifying NOLOCK on all statements in that transaction.

    using (var session = _sessionFactory.OpenSession())
    using (var transaction = session.BeginTransaction(IsolationLevel.ReadUncommitted))
    {
        // do work
    
        transaction.Commit();
    }