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?
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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With