跨方法事务方案

4.5.9.6功能

我们项目中如果是相同数据库,调用不同方法处理事务是不是很头痛了,需要把事务提取到 逻辑层进行统一事务提交,而SqlSugar提供了一个同线程共享一个SqlSugarClient功能,轻松实现了跨方法事务,让你的代码更加漂亮(注意:不同的线程就是不同的实例事务当然不会有效果)

SqlSugarClient db = new SqlSugarClient(
                new ConnectionConfig() {
                    ConnectionString = Config.ConnectionString,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    IsShardSameThread= true //设为true相同线程是同一个SqlConnection
                });
           
return db;


注意:同一个线程内共享一个DB对象时不能用Dispose或者using ,这样下面的方法就不能用了,可以用自动释放或者close释放数据库


完整例子:

  public class SharedConnection : DemoBase
    {
        public static void Init()
        {
            StudentDal studentDal = new StudentDal();
            SchoolDal schoolDal = new SchoolDal();

            try
            {
                studentDal.BeginTran();

                Console.WriteLine("school Count:"+ schoolDal.GetSchoolCount());//输出0

                studentDal.AddStudent(new Student() { Name = "StudentTest" });
                
                schoolDal.AddSchool(new School() { Name = "SchoolTest" });//输出1

                Console.WriteLine("school Count:" + schoolDal.GetSchoolCount());

                throw new Exception("error");
            }
            catch (Exception ex)
            {
                studentDal.RollbackTran();
                Console.WriteLine("school Count:" + schoolDal.GetSchoolCount());
                //输出0 ,没错虽然不在同一个dal里面但是 studentDal 成功回滚了 schoolDal的插入操作
            }
        }


    }
    public class StudentDal : BaseDao
    {
        public void AddStudent(Student sudent)
        {
            db.Insertable(sudent).ExecuteCommand();
        }
    }
    public class SchoolDal : BaseDao
    {
        public void AddSchool(School school)
        {
            db.Insertable(school).ExecuteCommand();
        }
        public int GetSchoolCount()
        {
            return db.Queryable<School>().Count();
        }
    }

    public class BaseDao
    {

        public SqlSugar.SqlSugarClient db { get { return GetInstance(); } }
        public void BeginTran()
        {
            db.Ado.BeginTran();
        }
        public void CommitTran()
        {
            db.Ado.CommitTran();
        }
        public void RollbackTran()
        {
            db.Ado.RollbackTran();
        }
        public SqlSugarClient GetInstance()
        {
            SqlSugarClient db = new SqlSugarClient(
                new ConnectionConfig() {
                    ConnectionString = Config.ConnectionString,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    IsShardSameThread= true /*Shard Same Thread*/
                });
          
            return db;
        }
    }


收藏到朋友圈: