多租户

添加多个Db

当我们一个db对象不够用时我们可以通过2种方式添加多个Db

1.使用Add方式动态添加Db

var db = new SqlSugarClient(new ConnectionConfig(){
                   DbType = SqlSugar.DbType.SqlServer,
                   IsAutoCloseConnection = true,
                   ConnectionString = Config.ConnectionString2,
                   AopEvents = new AopEvents()
                   {
                        OnLogExecuting = (sql, p) =>
                        {
                        Console.WriteLine("Default db : " + sql);
                       }
                    }
                  });
  //添中一个新的数据库
  db.AddConnection(new ConnectionConfig(){
                DbType = SqlSugar.DbType.SqlServer,
                ConfigId = "1",//设置库的唯一标识
                IsAutoCloseConnection = true,
                ConnectionString = Config.ConnectionString2,
                AopEvents = new AopEvents()
                {
                    OnLogExecuting = (sql, p) =>
                    {
                        Console.WriteLine("db 1:" + sql);
                    }
                }
  });


2.一次性New多个db

SqlSugarClient db = new SqlSugarClient(new List<ConnectionConfig>()
{
    new ConnectionConfig(){ ConfigId=null, DbType=DbType.SqlServer, 
    ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true },
    new ConnectionConfig(){ ConfigId="1", DbType=DbType.MySql, 
    ConnectionString=Config.ConnectionString4 ,InitKeyType=InitKeyType.Attribute ,IsAutoCloseConnection=true}
});


如何使用多库

var mysqldb = db.GetConnection("1");//获取config为1的数据库对象
var sqlServerdb = db.GetConnection(null);//获取默认对象
mysqldb.Queryable<Order>().ToList();
sqlServerdb.Queryable<Order>().ToList();


多库事务

//下面2行代码要写在事务开启之前
var mysqldb = db.GetConnection("1");//获取ConfigId为1的数据库对象
var sqlServerdb = db.GetConnection(null);//获取默认对象

//开启事务 (不能是db.ado.BeginTran)
db.BeginTran();
            mysqldb.Insertable(new Order()
            {
                CreateTime = DateTime.Now,
                CustomId = 1,
                Name = "a",
                Price = 1
            }).ExecuteCommand();
            mysqldb.Queryable<Order>().ToList();
            sqlServerdb.Queryable<Order>().ToList();
//提交事务  (不能是db.ado.CommitTran)
db.CommitTran();