Tomboi88 / dapper-dot-net

Automatically exported from code.google.com/p/dapper-dot-net
Other
0 stars 0 forks source link

Sharing an NHibernate connection/transaction #68

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Hey guys,

I'm kind of going through the same process you did with L2S, slowly migrating 
my read queries from NH over to Dapper.

What I was hoping to do was make the use of the NH connection that I'm creating 
per session.

I can get access to the connection but when I try and execute a command through 
dapper I get:

"ExecuteReader requires the command to have a transaction when the connection 
assigned to the command is in a pending local transaction.  The Transaction 
property of the command has not been initialized."

This is because I begin and commit an NH transaction at the start/end of the 
request. 

I'm assuming I need to pass this transaction to the dapper Query method. Any 
ideas how I can get the underlying IDbConnection from either the IDbConnection 
or NH ISession?

Thanks
Ben

Original issue reported on code.google.com by b...@planetcloud.co.uk on 15 Oct 2011 at 3:05

GoogleCodeExporter commented 8 years ago
NH wraps the underlying transaction away from you with no documented way to 
grab the IDbTransaction.

There's a hack to get it though. You can enlist a dummy command and grab the 
transaction from the command. Ayende gives the code to do that in this blog 
post:
http://ayende.com/blog/1583/i-hate-this-code

Original comment by joel.du...@gmail.com on 19 Sep 2012 at 6:10

GoogleCodeExporter commented 8 years ago
Any ideas how to fix this problem?

Original comment by fedoseev...@gmail.com on 7 Aug 2014 at 8:44

GoogleCodeExporter commented 8 years ago
By... using the hack already posted? 
http://ayende.com/blog/1583/i-hate-this-code

I'm not planning on taking a dependency on NHibernate to automate it, but you 
could make dapper extension methods on `ISession` that do basically the same, 
i.e.

    public static IEnumerable<T> Query<T>(this ISession session, ...)
    {
        IDbConnection conn;
        IDbTransaction tran;
        using(IDbCommand command = session.Connection.CreateCommand())
        {
            session.Transaction.Enlist(command);
            conn = command.Connection;
            tran = command.Transaction;            
        }
        return conn.Query<T>(..., transaction: tran);
    }

Not something I think we can solve inside the library, though - unless someone 
wants to propose a Dapper.NHibernate...

Original comment by marc.gravell on 7 Aug 2014 at 10:04

GoogleCodeExporter commented 8 years ago
Thank you. I will try this solution. If it would be ok - I'll contribute 
Dapper.NHibernate. why not :)

Original comment by fedoseev...@gmail.com on 8 Aug 2014 at 1:22