2017年7月25日 星期二

[.NET] Dapper - Transaction

 .NET    Dapper  


Introduction


Let’s see how to use transaction in Dapper.


Environment

Dapper 1.50.2



Implement


The sample codes are as following, remember to open the connection before executing the SQL.

Sql Connection Factory

public static class SqlConnectionFactory
{
        private static string _connStr = "Data Source=.;Initial Catalog=JB;Integrated Security=True";

        public static SqlConnection Create()
        {
            return new SqlConnection(_connStr);
        }
}



Transaction

int affectedRows = 0;

using (var cn = SqlConnectionFactory.Create())
{
                cn.Open();

                var sql = "INSERT INTO Citys(Id, Name) VALUES(@Id,@Name)";
                using (var transaction = cn.BeginTransaction())
                {
                    affectedRows = cn.Execute(sql,
                        new { Id = city.Id, Name = city.Name },
                        transaction: transaction);

                    transaction.Commit();

                }
}


TransactionScope


using (var transaction = new TransactionScope())
{
                var sqlInsertCity = "INSERT INTO Citys(Id, Name) VALUES(@Id,@Name)";
                var sqlInsertCustomer = "INSERT INTO Customers(Name,Age,Description) VALUES(@Name,@Age,@Description)";


                using (var cn = SqlConnectionFactory.Create())
                {
                    cn.Open();

                    cn.Execute(sqlInsertCity,
                             new { Id = city.Id, Name = city.Name });


                    cn.Execute(sqlInsertCustomer,
                        new { Name = cust.Name, Age = cust.Age, Description = cust.Description });
                }

                transaction.Complete();
}






Reference





沒有留言:

張貼留言