I would like to run multiple insert statements on multiple tables. I am using dapper.net. I don't see any way to handle transactions with dapper.net.
Please share your ideas on how to use transactions with dapper.net.
I would like to run multiple insert statements on multiple tables. I am using dapper.net. I don't see any way to handle transactions with dapper.net.
Please share your ideas on how to use transactions with dapper.net.
Daniel's answer worked as expected for me. For completeness, here's a snippet that demonstrates commit and rollback using a transaction scope and dapper:
Considering all your tables are in single database, I disagree with
TransactionScope
solution suggested in some answers here. Refer this answer.TransactionScope
is generally used for distributed transactions; transaction spanning different databases may be on different system. This needs some configurations on operating system and SQL Server without which this will not work. This is not recommended if all your queries are against single instance of database.But, with single database this may be useful when you need to include the code in transaction that is not under your control. With single database, it does not need special configurations either.
connection.BeginTransaction
is ADO.NET syntax to implement transaction (in C#, VB.NET etc.) against single database. This does not work across multiple databases.So,
connection.BeginTransaction()
is better way to go.Even the better way to handle the transaction is to implement UnitOfWork as explained in this answer.
Here the code snippet:
Note that you need to add reference to
System.Transactions
assembly because it is not referenced by default.You should be able to use
TransactionScope
since Dapper runs just ADO.NET commands.I preferred to use a more intuitive approach by getting the transaction directly from the connection: