Dapper总结(二)---事务和存储过程

一  dapper使用事务

 1  string sql1 = "insert into UserInfo values('user8',27,'s')";
 2             string sql2 = "insert into RoleInfo values('新角色2')";
 3             conn.Open();//在dapper中使用事务,需要手动打开连接
 4             IDbTransaction transaction = conn.BeginTransaction();//开启一个事务
 5             try
 6             {
 7                 conn.Execute(sql2, null, transaction);
 8                 conn.Execute(sql1, null, transaction);
 9                 
10                 transaction.Commit();//都执行成功时提交
11                 Console.WriteLine("Sucess");
12             }
13             catch (Exception ex)
14             {
15 
16                 transaction.Rollback();//只要有一条执行失败,执行回滚
17                 Console.WriteLine("Fail");
18             }
19             conn.Close();

二  dapper执行存储过程

1、有输入输出参数的存储过程

(1)创建存储过程

--插入新用户的存储过程,用户名存在就不插入
create proc sp_insertUser 
    @username nvarchar(50),
    @roleid int ,
    @age int,
    @count int out
as
begin
    declare @c int;
    select @c=COUNT(*) from UserInfo where UserName=@username;
    if(@c!=0)
        set @count =0;
    else
        begin 
            insert into UserInfo values(@username,@age,@roleid);
            set @count=1;
        end    
end
GO

(2)c#中使用dapper执行

 1         //设置参数 (input为默认参数类型,可以不写的)
 2             DynamicParameters dp = new DynamicParameters();
 3             dp.Add("@username", "newuser", DbType.String, ParameterDirection.Input, 50);
 4             dp.Add("@age", 20, DbType.Int16, ParameterDirection.Input);
 5             dp.Add("@roleid", 2, DbType.Int16, ParameterDirection.Input);
 6             dp.Add("@count", 2, DbType.Int16, ParameterDirection.Output);
 7 
 8            //执行存储过程
 9             var res = conn.Execute("sp_insertUser", dp, null, null, CommandType.StoredProcedure);
10             int count = dp.Get<int>("@count");//获取output参数的值        

2、无参返回多个结果集

(1)创建存储过程

--获取用户和角色表中的所有数据
create procedure sp_getUsesAndRoles
as
begin
    select * from UserInfo;
    select * from RoleInfo;
end

(2)c#中使用dapper执行

1      //获取多个结果集
2             Dapper.SqlMapper.GridReader res = conn.QueryMultiple("sp_getUsesAndRoles", null, null, null, CommandType.StoredProcedure);
3 
4             //read方法获取user和roles
5             IEnumerable<UserInfo> users = res.Read<UserInfo>();
6             IEnumerable<RoleInfo> roles = res.Read<RoleInfo>();
原文地址:https://www.cnblogs.com/wyy1234/p/9078859.html