Skip to content

Create database operation object

果糖网 edited this page Nov 1, 2021 · 5 revisions

Database operation object (Non-thread-safe)

 SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
 {
            ConnectionString = "Server=.xxxxx", 
            DbType = DbType.SqlServer,  
            IsAutoCloseConnection = true,
            LanguageType= LanguageType.English 
 });

Database operation object (Singleton , thread-safe)

 static SqlSugarScope scope= new SqlSugarScope(new ConnectionConfig()
 {
            ConnectionString = "Server=.xxxxx", 
            DbType = DbType.SqlServer, 
            IsAutoCloseConnection = true,
            LanguageType= LanguageType.English   
 },
  db=> {
      // A Global configuration
      // db.Aop.xxx=xxxx..
  });
  // B current context configuration
  //scope.Aop.xxx=xxxx..
  
  Task.Run(()=>{
    scope.Queryable<T>().ToList();//A
  });
  //A&B

use case

  //create database object
     SqlSugarClient db = new SqlSugarClient(new ConnectionConfig(){
           ConnectionString = "...", 
           DbType = DbType.SqlServer,
           LanguageType= LanguageType.English ,
           IsAutoCloseConnection = true});
      
     //aop print sql
     db.Aop.OnLogExecuting = (sql, pars) =>
     {
       Console.WriteLine(sql); 
      }
            
     //Query
     var list = db.Queryable<Student>().ToList();
      
     //Insert
     db.Insertable(new Student() { SchoolId = 1, Name = "jack" }).ExecuteCommand();
      
     //Update
     db.Updateable(new Student() { Id = 1, SchoolId = 2, Name = "jack2" }).ExecuteCommand();
      
     //Delete
     db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();