views:

39

answers:

2

Background: I am using Nhibernate in an ASP.NET MVC application with an open-session-in-view pattern and I need to use raw ADO.NET to execute some performance-critical database operations.

I'm somewhat confused about how I should be getting my connection instance as I've seen two different methods in numerous blog posts.

Do I want to use:

var connection = Session.Connection;

Or:

var connection = ((ISessionFactoryImplementor)sessionFactory).ConnectionProvider.GetConnection();

I can't seem to find a conclusive answer anywhere and I'm hoping that someone with some extensive NHibernate experience can chime in here.

+3  A: 

If you already have a session, use the connection from it.

That will also allow you to share the transaction (if one is open) by enlisting your commands on it.

Diego Mijelshon
@Diego: Is it possible to use an entirely different transaction using this connection without involving NHibernate at all? Ideally I'd like to use a READ UNCOMMITTED isolalation level because the read operation is rather performance-sensitive.
DanP
@DanP If you don't want to share anything with NH, why reference it at all? You can just use the same connection string... In any case, you *can* specify `IsolationLevel.ReadUncommitted` when beginning an NH transaction too...
Diego Mijelshon
@Deigo: Makes sense; thanks.
DanP
+1  A: 

i'm using something in the lines of (also uses the underlying already-open transaction)

SqlCommand command = new SqlCommand(updateString, (SqlConnection)NHibernateSession.Connection);
command.Parameters.AddRange(parameters.ToArray());

try
{
    ITransaction tx = NHibernateSession.Transaction;
    tx.Enlist(command);
    command.ExecuteNonQuery();
}
catch (SqlException)
{
    NHibernateSessionManager.Instance.RollbackTransaction();
    throw;
}
Jaguar
@Jarguar: thanks for the example - much appreciated!
DanP