5

How do I create a transaction if my DAL is using dapper-dot-net?

My c# winform application will be used in network and the data will be saved to a central sql server.

My use case requires use of transactions. Can I do this using dapper, or will I need to use something like NHibernate?

Also, is there any risk or limitation with this framework if I am using stored procedures? Will I need to change my approach due any possible limitations?

2 Answers 2

9

I haven't run into any limitations with using sprocs and the risks you have with dapper are the same risks you would have with sprocs

Here is a simple example on how to use transactions with dapper

using (var connection = Db.GetConnection()) { connection.Open(); IDbTransaction transaction = connection.BeginTransaction(); try { var newId= connection.Query<int>(@"Select id from table1 where id=@id", new{id}, transaction).Single(); connection.Execute(@"INSERT into table1 ...",new {p1, p2}, transaction); connection.Execute(@"INSERT into table2 ...",new {p1, p2}, transaction); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); } } 
Sign up to request clarification or add additional context in comments.

3 Comments

:) I see I forgot to declare the transaction as IDbTransaction.
Thanks for your comments. Also, I hope, there will not be any limitation or issue while using stored procedure. Actually, i am new with drapper so, i asked it.
@DPSoni it will behave identically to any other ADO.NET usage
3

dapper can use both ado.net transactions and implicit transactions. For ado.net transactions, just create the transaction normally and provide it via the transaction parameter that is available on the main methods. For implicit transactions, just use TransactionScope normally.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.