看了《Dapper从入门到精通》后的总结

 

(1)Dapper 是直接扩展 IDBConnection,而且是单独一个文件,可以直接嵌入到项目中使用。

(2)通过手写sql语句,调用execute方法添加数据,返回的是影响的行数;通过实体,调用insert方法添加数据,返回的是主键值。

 

(3)在IDBconnection中使用事务,主要注意在执行 Insert 方法时传入Transaction,用try...catch捕获异常,并在catch块调用Rollback(否则的话会出现部分提交的情况)。

例:

public bool InsertWithTran()
        {
            using (var conn = Connection)
            {
               int _departmentid = 0, _employeeid = 0,_rnum=0;
                var _departmentname = new t_department { departmentname = "应用开发部ENTITY", introduce = "应用开发部主要开始公司的应用平台" };
                var _employee = new t_employee {displayname = "Micro",email ="1441299@qq.com",loginname ="Micro",password = "66778899",mobile = "123456789"};
                conn.Open();
                var _tran=conn.BeginTransaction();
                try
                {
                    _departmentid=conn.Insert(_departmentname, transaction: _tran).Value;
                    ++_rnum;
                    _employeeid = conn.Insert(_employee, transaction: _tran).Value;
                    ++_rnum;
                    conn.Insert(new t_derelation { departmentid = _departmentid, employeeid = _employeeid }, transaction: _tran);
                    ++_rnum;
                    _tran.Commit();
                }
                catch
                {
                    _rnum = 0;
                    _tran.Rollback();
                }
                return _rnum > 0;
            }
        }
View Code

相关文章:

  • 2021-08-10
  • 2022-12-23
  • 2022-01-17
  • 2022-12-23
  • 2021-10-08
  • 2021-06-16
  • 2021-11-17
猜你喜欢
  • 2021-10-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-17
  • 2022-02-27
  • 2021-07-23
相关资源
相似解决方案