Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Dapper need a reference to the transaction when executing a query?

Tags:

c#

dapper

Just looking through this tutorial: https://www.davepaquette.com/archive/2019/02/06/managing-transactions-in-dapper.aspx

My understanding (without Dapper) is once you have a connection, you can open a transaction, then execute a bunch of statements, then either commit or roll back the transaction. Those queries don't need to reference the transaction because the connection already 'knows' about it.

So why does Dapper need the transaction every time some action is performed?

like image 674
Chechy Levas Avatar asked Oct 31 '20 09:10

Chechy Levas


1 Answers

Dapper doesn't change anything about the fundamental ADO.NET model, so if your operation inside a transaction fails if you don't explicitly pass the transaction to Dapper, then that is an ADO.NET thing, and the same operation would fail in exactly the same way without Dapper. All Dapper does is set the Transaction property on the command.

Or to put it another way: I believe your understanding is incorrect here. I agree with you that your understanding and expectation is reasonable though, and I'm not aware of any good reason that the command should even need to know about the transaction, which is ultimately a connection concern. But: I don't make the rules :/

Note that it is possible to use a "decorator" pattern in ADO.NET (mini-profiler does this, for example), so in theory it would be possible to create a connection wrapper that tracks the transaction for you, and have the command retrieve the transaction and attach it automatically when operations are performed. It probably isn't much work if you start from mini-profiler's base type.

like image 168
Marc Gravell Avatar answered Oct 10 '22 10:10

Marc Gravell