輕量級.NET ORM、高效能.NET ORM 之 SqlSugar 開源ORM - ASP.NET

孫凱旋發表於2015-07-22

 3.0最新API:

http://www.cnblogs.com/sunkaixuan/p/5911334.html

 

1、前言/Preface

SqlSugar從去年到現在已經一年了,版本從1.0升到了現在的2.8 ,這是一個穩定版本 ,有數家公司已經專案上線,在這裡我將SqlSugar的功能重新整理成一篇新的貼子,希望大家喜歡。

 公司團隊專案、產品已經完全拋棄EF,SqlSugar定位不是ORM,而是為了方便的讓你去寫Sql。

媲美原生ADO.NET的效能、簡潔的語法和支援Json 、Dynamic、 List<T>、 List<string[]>、 ValueType和  Dictionary 等多種型別的返回值 有很多亮點。

 

 GitHub下載地址:

MSSQL .NET 4.0+

https://github.com/sunkaixuan/SqlSugar 

MSSQL .NET Core 版本

https://github.com/sunkaixuan/ASP_NET_CORE_ORM_SqlSugar

 Sqlite .net4.0+

https://github.com/sunkaixuan/SqliteSugar

MYSQL .NET 4.0+

http://www.cnblogs.com/sunkaixuan/p/5747259.html

ORACLE.NET 4.0+

https://github.com/sunkaixuan/OracleSugar

 ORACLE CORE ,MYSQL CORE,SQLITE  CORE 待開發

 

最新更新:

 

3.0.02

可以設定生成實體的摘要

    var temSummary = ClassTemplate.ClassFieldSummaryTemplate;

 

批量新增別名表功能

     //批量設定別名表
     //db.ClassGenerating.ForeachTables(db, tableName =>
      //{
                //    db.AddMappingTable(new KeyValue() { Key = tableName.Replace("bbs.",""), Value =  tableName }); //key實體名,value表名
     //});

 

別名列功能

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewTest.Dao;
using System.Data.SqlClient;
using SqlSugar;
namespace NewTest.Demos
{
    //別名列的功能
    public class MappingColumns : IDemos
    {

        public void Init()
        {
            Console.WriteLine("啟動MappingColumns.Init");

            //全域性設定
            using (var db = SugarFactory.GetInstance())
            {
                var list = db.Queryable<Student>().Where(it=>it.classId==1).ToList();
            }
        }

        public class Student
        {

            //id
            public int classId { get; set; }

            //name
            public string className { get; set; }

            //sch_id
            public int classSchoolId { get; set; }

            public int isOk { get; set; }
        }

        /// <summary>
        /// 全域性配置別名列(不區分表)
        /// </summary>
        public class SugarConfigs
        {
            //key實體欄位名 value表欄位名 ,KEY唯一否則異常
            public static List<KeyValue> MpList = new List<KeyValue>(){
            new KeyValue(){ Key="classId", Value="id"},
            new KeyValue(){ Key="className", Value="name"},
            new KeyValue(){ Key="classSchoolId", Value="sch_id"}
            };
        }

        /// <summary>
        /// SqlSugar例項工廠
        /// </summary>
        public class SugarFactory
        {

            //禁止例項化
            private SugarFactory()
            {

            }
            public static SqlSugarClient GetInstance()
            {
                string connection = SugarDao.ConnectionString; //這裡可以動態根據cookies或session實現多庫切換
                var db = new SqlSugarClient(connection);
                //注意:只有啟動屬性對映才可以使用SetMappingColumns
                db.IsEnableAttributeMapping = true;
                db.SetMappingColumns(SugarConfigs.MpList);//設定關聯列 (引用地址賦值,每次賦值都只是儲存一個記憶體地址)
                return db;
            }
        }
    }
}
View Code

 

通過屬性設定別名表和別名列和欄位過濾

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewTest.Dao;
using Models;
using System.Data.SqlClient;
using SqlSugar;
namespace NewTest.Demos
{
    //通過屬性的方法設定別名表和別名欄位(主鍵和自添列都無需設定 SQLSUGAR會幫你自動處理)
    //注意:【屬性對映和 (SetMappingTables、SetMappingColumns)方式對映 2種選其中一,不清楚底層快取機質不建議同時使用】
    public class AttributesMapping : IDemos
    {

        public void Init()
        {
            Console.WriteLine("啟動AttributesMapping.Init");
            using (var db = DBManager.GetInstance())
            {

                //查詢
                var list = db.Queryable<TestStudent>()
                    .Where(it => it.className.Contains("")).OrderBy(it => it.classSchoolId).Select<V_Student>(it => new V_Student() { id = it.classId, name = it.className }).ToList();
                var list2 = db.Queryable<TestStudent>()
                    .JoinTable<TestSchool>((s1, s2) => s1.classSchoolId == s2.classId)
                    .OrderBy<TestSchool>((s1, s2) => s1.classId)
                    .Select<TestStudent, TestSchool, V_Student>((s1, s2) => new V_Student() { id = s1.classId, name = s1.className, SchoolName = s2.className }).ToList();

                //新增
                TestStudent s = new TestStudent();
                s.className = "屬性名";
                s.classSchoolId = 1;
                var id = db.Insert(s);
                s.classId = id.ObjToInt();

                //更新
                db.Update(s);
                db.Update<TestStudent, int>(s, 100);
                db.Update<TestStudent>(s, it => it.classId == 100);
                db.SqlBulkReplace(new List<TestStudent>() { s });

                //刪除
                db.Delete<TestStudent>(it => it.classId == 100);
            }
        }

        /// <summary>
        /// 屬性只作為初始化對映,SetMappingTables和SetMappingColumns可以覆蓋
        /// </summary>
        [SugarMapping(TableName = "Student")]
        public class TestStudent
        {

            [SugarMapping(ColumnName = "id")]
            public int classId { get; set; }

            [SugarMapping(ColumnName = "name")]
            public string className { get; set; }

            [SugarMapping(ColumnName = "sch_id")]
            public int classSchoolId { get; set; }

            public int isOk { get; set; }

            /// <summary>
            /// 資料庫並沒有這一列
            /// </summary>
            public string errorField { get; set; }
        }

 
        [SugarMapping(TableName = "School")]
        public class TestSchool
        {

            [SugarMapping(ColumnName = "id")]
            public int classId { get; set; }

            [SugarMapping(ColumnName = "name")]
            public string className { get; set; }

            public int AreaId = 1;
        }
    }

    public class DBManager
    {

        public static SqlSugarClient GetInstance()
        {
            var db = new SqlSugarClient(SugarDao.ConnectionString);
            db.IsEnableAttributeMapping = true;//啟用屬性對映
            db.IsIgnoreErrorColumns = true;//忽略非資料庫列



            db.IsEnableLogEvent = true;//啟用日誌事件
            db.LogEventStarting = (sql, par) => { Console.WriteLine(sql + " " + par + "\r\n"); };


            return db;
        }
    }
}
View Code

 

拉姆達支援了 contains

 db.Update<School>(new { name = "藍翔2" }, it => array.Contains(it.id))

 

新增了高效能批量更新

db.SqlBulkReplace

 

2.9.1.0

新增了SQL日誌和監控功能

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewTest.Dao;
using Models;
using System.Data.SqlClient;
using SqlSugar;

namespace NewTest.Demos
{
    //日誌記錄功能
    public class Log : IDemos
    {
       
        public void Init()
        {
            Console.WriteLine("啟動Log.Init");
            using (var db = SugarDemoDao.GetInstance())
            {

                var a1 = db.Queryable<Student>().Where(it => it.id == 1).ToList();
                var a2 = db.Queryable<Student>().OrderBy(it => it.id).ToList();
            }
        }

        public class SugarConfigs
        {
            public static Action<string, string> LogEventStarting = (sql, pars) =>
            {
                Console.WriteLine("starting:" + sql + " " + pars);
                
                using (var db = SugarDemoDao.GetInstance())
                {
                    //日誌記錄件事件裡面用到資料庫操作 IsEnableLogEvent一定要為false否則將引起死迴圈,並且要新開一個資料例項 像我這樣寫就沒問題。
                    db.IsEnableLogEvent = false;
                    db.ExecuteCommand("select 1");
                }
            };
            public static Action<string, string> LogEventCompleted = (sql, pars) =>
            {
                Console.WriteLine("completed:" + sql + " " + pars);
            };
        }

        /// <summary>
        /// SqlSugar
        /// </summary>
        public class SugarDemoDao
        {

            public static SqlSugarClient GetInstance()
            {
                var db = new SqlSugarClient(SugarDao.ConnectionString);
                db.IsEnableLogEvent = true;//啟用日誌事件
                db.LogEventStarting = SugarConfigs.LogEventStarting;
                db.LogEventCompleted = SugarConfigs.LogEventCompleted;
                return db;
            }
        }
    }
}
日誌記錄功能

 

大量語法優化

以前 .select<oldT,newT>(it=>newT{ id=it.id})可以寫成.select<newT>(it=>newT{ id=it.id})

以前 .select<T,int>(it=>it.id)可以寫成.select<int>(it=>it.id);

Join也進行了美化可以不用寫第一個T

 //2表關聯查詢
                var jList = db.Queryable<Student>()
                .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) //預設left join
                .Where<School>((s1, s2) => s1.id == 1)
                .Select("s1.*,s2.name as schName")
                .ToDynamic();

                /*等於同於
                 SELECT s1.*,s2.name as schName 
                 FROM [Student]  s1 
                 LEFT JOIN [School]  s2 ON  s1.sch_id  = s2.id 
                 WHERE  s1.id  = 1 */

                //2表關聯查詢並分頁
                var jList2 = db.Queryable<Student>()
                .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) //預設left join
                    //如果要用inner join這麼寫
                    //.JoinTable<School>((s1, s2) => s1.sch_id == s2.id ,JoinType.INNER)
                .Where<School>((s1, s2) => s1.id > 1)
                .OrderBy(s1 => s1.name)
                .Skip(10)
                .Take(20)
                .Select("s1.*,s2.name as schName")
                .ToDynamic();

                //3表查詢並分頁
                var jList3 = db.Queryable<Student>()
               .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) // left join  School s2  on s1.id=s2.id
               .JoinTable<School>((s1, s3) => s1.sch_id == s3.id) // left join  School s3  on s1.id=s3.id
               .Where<School>((s1, s2) => s1.id > 1)  // where s1.id>1
               .Where(s1 => s1.id > 0)
               .OrderBy<School>((s1, s2) => s1.id) //order by s1.id 多個order可以  .oderBy().orderby 疊加 
               .Skip(10)
               .Take(20)
               .Select("s1.*,s2.name as schName,s3.name as schName2")//select目前只支援這種寫法
               .ToDynamic();


                //上面的方式都是與第一張表join,第三張表想與第二張表join寫法如下
                List<V_Student> jList4 =
                 db.Queryable<Student>()
                 .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) // left join  School s2  on s1.id=s2.id
                 .JoinTable<School, Area>((s1, s2, a1) => a1.id == s2.AreaId)// left join  Area a1  on a1.id=s2.AreaId  第三張表與第二張表關聯
                 .JoinTable<Area, School>((s1, a1, s3) => a1.id == s3.AreaId)// left join  School s3  on a1.id=s3.AreaId  第四第表第三張表關聯
                 .JoinTable<School>((s1, s4) => s1.sch_id == s4.id) // left join  School s2  on s1.id=s4.id
                 .Select<School, Area, V_Student>((s1, s2, a1) => new V_Student { id = s1.id, name = s1.name, SchoolName = s2.name, AreaName = a1.name }).ToList();
JoinTable新寫法

 

 

 

2.8.01設定不插入列

2.8.0.0 強化了 SELECT 新容器轉換功能,以前只能 id=it.id 這種等值操作,現在支援了型別轉換函式,另外還支援了外部傳參和內部硬編碼的寫法

  //新容器轉換函式的支援,例子外其它寫法暫不支援 
                var f1 = db.Queryable<InsertTest>().Select<InsertTest, Student>(it => new Student()
                {
                    name = it.d1.ObjToString(),
                    id = it.int1.ObjToInt() // 支援ObjToXXX 所有函式

                }).ToList();

                var f2 = db.Queryable<InsertTest>().Select<InsertTest, Student>(it => new Student()
                {
                    name = Convert.ToString(it.d1),//支援Convet.ToXX所有函式
                    id = it.int1.ObjToInt(),
                    sex = Convert.ToString(it.d1),

                }).ToList();

                var f3 = db.Queryable<InsertTest>()
                    .JoinTable<InsertTest, InsertTest>((i1, i2) => i1.id == i2.id)
                    .Select<InsertTest, InsertTest, Student>((i1, i2) => new Student()
                {
                    name = Convert.ToString( i1.d1), //多表查詢例子
                    id = i1.int1.ObjToInt( ),
                    sex = Convert.ToString( i2.d1 ),

                }).ToList();

                //Select 外部引數用法
                var f4 = db.Queryable<InsertTest>().Where("1=1", new { id = id + 100 }).Select<InsertTest, Student>(it => new Student()
               {
                   id = "@id".ObjToInt(), //取的是 id+100 的值
                   name = "張三",//內部引數可以直接寫
                   sex = it.txt,
                   sch_id=it.id

               }).ToList();
                var f6 = db.Queryable<InsertTest>()
               .JoinTable<InsertTest, InsertTest>((i1, i2) => i1.id == i2.id)
               .Where("1=1", new { id = 100, name = "張三",isOk=true }) //外部傳參給@id
               .Select<InsertTest, InsertTest, Student>((i1, i2) => new Student()
               {
                   name = "@name".ObjToString(), //多表查詢例子
                   id = "@id".ObjToInt(),
                   sex = i2.txt,
                   sch_id = 1,
                   isOk = "@isOk".ObjToBool()

               }).ToList();
View Code

 

2.7.1.3  更新了SqlSugar所有的函式的備註、類的備註

 

OracleSugar已經上傳NUGET GIT文章最下方有地址

 

2.7.08  支援了字典引數

     List<Student> list2 = db.SqlQuery<Student>("select * from Student where id=@id", new { id = 1 }); 其中new { id = 1 }可以改成 Dictionary<string, object>(){{id,1}}

     db.Update<School>(new { name = "藍翔14" }, it => it.id == 14); 其中 new { name = "藍翔14" } 可以改成 Dictionary<string, object>(){{name,"藍翔14"}}

     這樣做有什麼好處呢?動態許可權的時候弱型別會比較好處理

 

 

 2.7.1.0 JoinTable支援了字串,可以做更復雜的查詢例如:

using (SqlSugarClient db = SugarDao.GetInstance())
            {

                var childQuery = db.Queryable<Area>().Where("id=@id").Select(it => new { id=it.id }).ToSql();//建立子查詢SQL
                string childTableName=string.Format("({0})",childQuery.Key);//將SQL語句用()包成表


                var queryable = db.Queryable<Student>()
                 .JoinTable<Student, School>((s1, s2) => s1.sch_id == s2.id) 
                 .JoinTable(childTableName, "a1", "a1.id=s2.areaid", new { id = 1 }, JoinType.INNER)
                 .OrderBy(s1 => s1.id);
              

                //SELECT * FROM  ( 
                
                                     //SELECT newid = s1.id, studentName = s1.name, schoolName = s2.name, areaName = a1.name ,row_index=ROW_NUMBER() OVER(ORDER BY s1.id ASC ) FROM [Student]   s1 
                                     //LEFT JOIN School  s2 ON  ( s1.sch_id  = s2.id )    
                                     //INNER JOIN (SELECT *  FROM [Area]   WHERE 1=1  AND id=@id   ) a1 ON a1.id=s2.areaid    WHERE 1=1
                                //
                                //) t WHERE t.row_index BETWEEN 1 AND 200

                 var list= queryable.Select<Student, School, Area, classNew>((s1, s2, a1) => new classNew { newid = s1.id, studentName = s1.name, schoolName = s2.name, areaName = a1.name })
                     .ToPageList(0,200);

                 var count=queryable.Count();
            }
joinTable高階查詢

 

 

優點:

1、高效能,達到原生最高水準,比SqlHelper效能要高,比Dapper快30% 比EF快50%

2、支援多種資料庫 ,sql版本更新最快,其它會定期更新,可以在多種資料庫用一種程式設計方式

3、支援.net Core

4、支援多庫平行計算

5、帶有實體生成函式和T4模版生成實體

6、無需任何配置 ,還你一個乾淨的model,可以沒有主鍵 ,也可以有多個主鍵 ,或者多個自增列

7、輕量級 SqlSugar ORM 一個DLL只有150 K ,一個EF DLL有5M ,一個EF擴充套件DLL有500多K

 

 

 

 

2、功能介紹/Product function introduction

 

查詢/Search

 

1、Queryable用於拉姆達運算元據庫

 

2、SqlQuery用於執行SQL和儲存過程

 

3、Sqlable一種更新近SQL的寫法

 

1、Queryable 用於拉姆達表示式操作(支援Join多表)    / Select single table or view

 using (var db = SugarDao.GetInstance())
 {


                //---------Queryable<T>,擴充套件函式查詢---------//

                //針對單表或者檢視查詢

                //查詢所有
                var student = db.Queryable<Student>().ToList();
                var studentDynamic = db.Queryable<Student>().ToDynamic();
                var studentJson = db.Queryable<Student>().ToJson();

                //查詢單條
                var single = db.Queryable<Student>().Single(c => c.id == 1);
                //查詢單條沒有記錄返回空物件
                var singleOrDefault = db.Queryable<Student>().SingleOrDefault(c => c.id == 11111111);
                //查詢單條沒有記錄返回空物件
                var single2 = db.Queryable<Student>().Where(c => c.id == 1).SingleOrDefault();

                //查詢第一條
                var first = db.Queryable<Student>().Where(c => c.id == 1).First();
                var first2 = db.Queryable<Student>().Where(c => c.id == 1).FirstOrDefault();

                //取11-20條
                var page1 = db.Queryable<Student>().Where(c => c.id > 10).OrderBy(it => it.id).Skip(10).Take(10).ToList();

                //取11-20條  等於 Skip(pageIndex-1)*pageSize).Take(pageSize) 等於  between (pageIndex-1)*pageSize and  pageIndex*pageSize
                var page2 = db.Queryable<Student>().Where(c => c.id > 10).OrderBy(it => it.id).ToPageList(2, 10);

                //查詢條數
                var count = db.Queryable<Student>().Where(c => c.id > 10).Count();

                //從第2條開始以後取所有
                var skip = db.Queryable<Student>().Where(c => c.id > 10).OrderBy(it => it.id).Skip(2).ToList();

                //取前2條
                var take = db.Queryable<Student>().Where(c => c.id > 10).OrderBy(it => it.id).Take(2).ToList();

                // Not like 
                string conval = "a";
                var notLike = db.Queryable<Student>().Where(c => !c.name.Contains(conval.ToString())).ToList();
                //Like
                conval = "";
                var like = db.Queryable<Student>().Where(c => c.name.Contains(conval)).ToList();

                //支援字串Where 讓你解決,更復雜的查詢
                var student12 = db.Queryable<Student>().Where(c => "a" == "a").Where("id>@id", new { id = 1 }).ToList();
                var student13 = db.Queryable<Student>().Where(c => "a" == "a").Where("id>100 and id in( select 1)").ToList();


                //存在記錄反回true,則否返回false
                bool isAny100 = db.Queryable<Student>().Any(c => c.id == 100);
                bool isAny1 = db.Queryable<Student>().Any(c => c.id == 1);


                //獲取最大Id
                object maxId = db.Queryable<Student>().Max(it => it.id);
                int maxId1 = db.Queryable<Student>().Max(it => it.id).ObjToInt();//拉姆達
                int maxId2 = db.Queryable<Student>().Max<int>("id"); //字串寫法

                //獲取最小
                int minId1 = db.Queryable<Student>().Where(c => c.id > 0).Min(it => it.id).ObjToInt();//拉姆達
                int minId2 = db.Queryable<Student>().Where(c => c.id > 0).Min<int>("id");//字串寫法


                //order By 
                var orderList = db.Queryable<Student>().OrderBy("id desc,name asc").ToList();//字串支援多個排序
                //可以多個order by表達示
                var order2List = db.Queryable<Student>().OrderBy(it => it.name).OrderBy(it => it.id, OrderByType.desc).ToList(); // order by name as ,order by id desc

                //In
                var intArray = new[] { "5", "2", "3" };
                var intList = intArray.ToList();
                var listnew = db.Queryable<Student>().Where(it => intArray.Contains(it.name)).ToList();
                var list0 = db.Queryable<Student>().In(it => it.id, 1, 2, 3).ToList();
                var list1 = db.Queryable<Student>().In(it => it.id, intArray).ToList();
                var list2 = db.Queryable<Student>().In("id", intArray).ToList();
                var list3 = db.Queryable<Student>().In(it => it.id, intList).ToList();
                var list4 = db.Queryable<Student>().In("id", intList).ToList();

                //分組查詢
                var list7 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy(it => it.sex).Select("sex,count(*) Count").ToDynamic();
                var list8 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy(it => it.sex).GroupBy(it => it.id).Select("id,sex,count(*) Count").ToDynamic();
                List<StudentGroup> list9 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy(it => it.sex).Select<StudentGroup>("Sex,count(*) Count").ToList();
                List<StudentGroup> list10 = db.Queryable<Student>().Where(c => c.id < 20).GroupBy("sex").Select<StudentGroup>("Sex,count(*) Count").ToList();
                //SELECT Sex,Count=count(*)  FROM Student  WHERE 1=1  AND  (id < 20)    GROUP BY Sex --生成結果



                //2表關聯查詢
                var jList = db.Queryable<Student>()
                .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) //預設left join
                .Where<School>((s1, s2) => s1.id == 1)
                .Select("s1.*,s2.name as schName")
                .ToDynamic();

                /*等於同於
                 SELECT s1.*,s2.name as schName 
                 FROM [Student]  s1 
                 LEFT JOIN [School]  s2 ON  s1.sch_id  = s2.id 
                 WHERE  s1.id  = 1 */

                //2表關聯查詢並分頁
                var jList2 = db.Queryable<Student>()
                .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) //預設left join
                    //如果要用inner join這麼寫
                    //.JoinTable<School>((s1, s2) => s1.sch_id == s2.id ,JoinType.INNER)
                .Where<School>((s1, s2) => s1.id > 1)
                .OrderBy(s1 => s1.name)
                .Skip(10)
                .Take(20)
                .Select("s1.*,s2.name as schName")
                .ToDynamic();

                //3表查詢並分頁
                var jList3 = db.Queryable<Student>()
               .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) // left join  School s2  on s1.id=s2.id
               .JoinTable<School>((s1, s3) => s1.sch_id == s3.id) // left join  School s3  on s1.id=s3.id
               .Where<School>((s1, s2) => s1.id > 1)  // where s1.id>1
               .Where(s1 => s1.id > 0)
               .OrderBy<School>((s1, s2) => s1.id) //order by s1.id 多個order可以  .oderBy().orderby 疊加 
               .Skip(10)
               .Take(20)
               .Select("s1.*,s2.name as schName,s3.name as schName2")//select目前只支援這種寫法
               .ToDynamic();


                //上面的方式都是與第一張表join,第三張表想與第二張表join寫法如下
                List<V_Student> jList4 =
                 db.Queryable<Student>()
                 .JoinTable<School>((s1, s2) => s1.sch_id == s2.id) // left join  School s2  on s1.id=s2.id
                 .JoinTable<School, Area>((s1, s2, a1) => a1.id == s2.AreaId)// left join  Area a1  on a1.id=s2.AreaId  第三張表與第二張表關聯
                 .JoinTable<Area, School>((s1, a1, s3) => a1.id == s3.AreaId)// left join  School s3  on a1.id=s3.AreaId  第四第表第三張表關聯
                 .JoinTable<School>((s1, s4) => s1.sch_id == s4.id) // left join  School s2  on s1.id=s4.id
                 .Select<School, Area, V_Student>((s1, s2, a1) => new V_Student { id = s1.id, name = s1.name, SchoolName = s2.name, AreaName = a1.name }).ToList();

                //等同於
                //SELECT id = s1.id, name = s1.name, SchoolName = s2.name, AreaName = a1.name  
                //FROM [Student]   s1 
                //LEFT JOIN School  s2 ON  ( s1.sch_id  = s2.id )    
                //LEFT JOIN Area  a1 ON  ( a1.id  = s2.AreaId )     //第三張表與第二張表關聯
                //LEFT JOIN School  s3 ON  ( a1.id  = s3.AreaId )   //第四張表與第三張表關聯
                //LEFT JOIN School  s4 ON  ( s1.sch_id  = s4.id )    
                //WHERE 1=1    


                //Join子查詢語句加分頁的寫法
                var childQuery = db.Queryable<Area>().Where("id=@id").Select(it => new { id = it.id }).ToSql();//建立子查詢SQL
                string childTableName = string.Format("({0})", childQuery.Key);//將SQL語句用()包成表
                var queryable = db.Queryable<Student>()
                 .JoinTable<School>((s1, s2) => s1.sch_id == s2.id)  //LEFT JOIN School  s2 ON  ( s1.sch_id  = s2.id )  
                 .JoinTable(childTableName, "a1", "a1.id=s2.areaid", new { id = 1 }, JoinType.INNER) //INNER JOIN (SELECT *  FROM [Area]   WHERE 1=1  AND id=@id   ) a1 ON a1.id=s2.areaid
                 .OrderBy(s1 => s1.id);

                var list = queryable.Select<School, Area, V_Student>((s1, s2, a1) => new V_Student { id = s1.id, name = s1.name, SchoolName = s2.name, AreaName = a1.name })
                    .ToPageList(0, 200);
                var count2 = list.Count;


                //拼接例子
                var queryable2 = db.Queryable<Student>().Where(it => true);
                if (maxId.ObjToInt() == 1)
                {
                    queryable2.Where(it => it.id == 1);
                }
                else
                {
                    queryable2.Where(it => it.id == 2);
                }
                var listJoin = queryable2.ToList();


                //queryable和SqlSugarClient解耦
                var par = new Queryable<Student>().Where(it => it.id == 1);//聲名沒有connection物件的Queryable
                par.DB = db;
                var listPar = par.ToList();


                //檢視生成的sql和引數
                var id = 1;
                var sqlAndPars = db.Queryable<Student>().Where(it => it.id == id).OrderBy(it => it.id).ToSql();



                //條件函式的支援(欄位暫不支援函式,只有引數支援) 目前只支援這麼多
                var par1 = "2015-1-1"; var par2 = "   我 有空格A, ";
                var r1 = db.Queryable<Student>().Where(it => it.name == par1.ObjToString()).ToSql(); //ObjToString會將null轉轉成""
                var r2 = db.Queryable<InsertTest>().Where(it => it.d1 == par1.ObjToDate()).ToSql();
                var r3 = db.Queryable<InsertTest>().Where(it => it.id == 1.ObjToInt()).ToSql();//ObjToInt會將null轉轉成0
                var r4 = db.Queryable<InsertTest>().Where(it => it.id == 2.ObjToDecimal()).ToSql();
                var r5 = db.Queryable<InsertTest>().Where(it => it.id == 3.ObjToMoney()).ToSql();
                var r6 = db.Queryable<InsertTest>().Where(it => it.v1 == par2.Trim()).ToSql();
                var convert1 = db.Queryable<Student>().Where(c => c.name == "a".ToString()).ToList();
                var convert2 = db.Queryable<Student>().Where(c => c.id == Convert.ToInt32("1")).ToList();
                var convert3 = db.Queryable<Student>().Where(c => c.name == par2.ToLower()).ToList();
                var convert4 = db.Queryable<Student>().Where(c => c.name == par2.ToUpper()).ToList();
                var convert5= db.Queryable<Student>().Where(c => DateTime.Now > Convert.ToDateTime("2015-1-1")).ToList();
                var c1 = db.Queryable<Student>().Where(c => c.name.Contains("a")).ToList();
                var c2 = db.Queryable<Student>().Where(c => c.name.StartsWith("a")).ToList();
                var c3 = db.Queryable<Student>().Where(c => c.name.EndsWith("a")).ToList();
                var c4 = db.Queryable<Student>().Where(c => !string.IsNullOrEmpty(c.name)).ToList();

  }

 

 

 

2、SqlQuery 用於執行原生SQL和儲存過程   /   Execution of native SQL

 using (var db = SugarDao.GetInstance())
 {
                //轉成list
                List<Student> list1 = db.SqlQuery<Student>("select * from Student");
                //轉成list帶參
                List<Student> list2 = db.SqlQuery<Student>("select * from Student where id=@id", new { id = 1 });
                //轉成dynamic
                dynamic list3 = db.SqlQueryDynamic("select * from student");
                //轉成json
                string list4 = db.SqlQueryJson("select * from student");
                //返回int
                var list5 = db.SqlQuery<int>("select top 1 id from Student").SingleOrDefault();
                //反回鍵值
                Dictionary<string, string> list6 = db.SqlQuery<KeyValuePair<string, string>>("select id,name from Student").ToDictionary(it => it.Key, it => it.Value);
                //反回List<string[]>
                var list7 = db.SqlQuery<string[]>("select top 1 id,name from Student").SingleOrDefault();
                //儲存過程
                var spResult = db.SqlQuery<School>("exec sp_school @p1,@p2", new { p1 = 1, p2 = 2 });

                //儲存過程加Output 
                var pars = SqlSugarTool.GetParameters(new { p1 = 1,p2=0 }); //將匿名物件轉成SqlParameter
                db.IsClearParameters = false;//禁止清除引數
                pars[1].Direction = ParameterDirection.Output; //將p2設為 output
                var spResult2 = db.SqlQuery<School>("exec sp_school @p1,@p2 output", pars);
                db.IsClearParameters = true;//啟動請動清除引數
                var outPutValue = pars[1].Value;//獲取output @p2的值

                //獲取第一行第一列的值
                string v1 = db.GetString("select '張三' as name");
                int v2 = db.GetInt("select 1 as name");
                double v3 = db.GetDouble("select 1 as name");
                decimal v4 = db.GetDecimal("select 1 as name");
                //....
            }

 

 

3、Sqlable 更貼近SQL的一種程式設計方式,適用於複雜查詢 / Complex query

//---------Sqlable,建立多表查詢---------//

                //多表查詢
                List<School> dataList = db.Sqlable()
                   .From("school", "s")
                   .Join("student", "st", "st.id", "s.id", JoinType.INNER)
                   .Join("student", "st2", "st2.id", "st.id", JoinType.LEFT)
                   .Where("s.id>100 and s.id<@id")
                   .Where("1=1")//可以多個WHERE
                   .SelectToList<School/*新的Model我這裡沒有所以寫的School*/>("st.*", new { id = 1 });

                //多表分頁
                List<School> dataPageList = db.Sqlable()
                    .From("school", "s")
                    .Join("student", "st", "st.id", "s.id", JoinType.INNER)
                    .Join("student", "st2", "st2.id", "st.id", JoinType.LEFT)
                    .Where("s.id>100 and s.id<100")
                    .SelectToPageList<School>("st.*", "s.id", 1, 10);

                //多表分頁WHERE加子查詢
                List<School> dataPageList2 = db.Sqlable()
                    .From("school", "s")
                    .Join("student", "st", "st.id", "s.id", JoinType.INNER)
                    .Join("student", "st2", "st2.id", "st.id", JoinType.LEFT)
                    .Where("s.id>100 and s.id<100 and s.id in (select 1 )" /*這裡面寫子查詢都可以*/)
                    .SelectToPageList<School>("st.*", "s.id", 1, 10);



                //--------轉成List Dynmaic 或者 Json-----//

                //不分頁
                var list1 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToDynamic("*", new { id = 1 });
                var list2 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToJson("*", new { id = 1 });
                var list3 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToDataTable("*", new { id = 1 });

                //分頁
                var list4 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToPageDynamic("s.*", "l.id", 1, 10, new { id = 1 });
                var list5 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToPageTable("s.*", "l.id", 1, 10, new { id = 1 });
                var list6 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToPageDynamic("s.*", "l.id", 1, 10, new { id = 1 });


                //--------拼接-----//
                Sqlable sable = db.Sqlable().From<Student>("s").Join<School>("l", "s.sch_id", "l.id", JoinType.INNER);
                string name = "a";
                int id = 1;
                if (!string.IsNullOrEmpty(name))
                {
                    sable = sable.Where("s.name=@name");
                }
                if (!string.IsNullOrEmpty(name))
                {
                    sable = sable.Where("s.id=@id or s.id=100");
                }
                if (id > 0)
                {
                    sable = sable.Where("l.id in (select top 10 id from school)");//where加子查詢
                }
                var pars = new { id = id, name = name };
                int pageCount = sable.Count(pars);
                var list7 = sable.SelectToPageList<Student>("s.*","l.id desc",1,20, pars);
多表查詢

 

4、新容器轉換 / To new container

 using (SqlSugarClient db = SugarDao.GetInstance())
            {

                //單表操作將Student轉換成V_Student
                var queryable = db.Queryable<Student>().Where(c => c.id < 10)
                    .Select<V_Student>(c => new V_Student { id = c.id, name = c.name, AreaName = "預設地區", SchoolName = "預設學校", SubjectName = "NET" });

                var list = queryable.ToList();
                var json = queryable.ToJson();
                var dynamic = queryable.ToDynamic();


                //多表操作將Student轉換成V_Student
                var queryable2 = db.Queryable<Student>()
                 .JoinTable<School>((s1, s2) => s1.sch_id == s2.id)
                 .Where<School>((s1, s2) => s2.id < 10)
                 .Select<School, V_Student>((s1, s2) => new V_Student() { id = s1.id, name = s1.name, AreaName = "預設地區", SchoolName = s2.name, SubjectName = "NET" });//select new 目前只支援這種寫法

                var list2 = queryable2.ToList();
                var json2 = queryable2.ToJson();
                var dynamic2 = queryable2.ToDynamic();


                //select字串 轉換成V_Student
                var list3 = db.Queryable<Student>()
               .JoinTable<School>((s1, s2) => s1.sch_id == s2.id)
               .Where(s1 => s1.id <= 3)
               .Select<V_Student>("s1.*,s2.name SchoolName")
               .ToList();

                //select字串 轉換成Json
                var json3 = db.Queryable<Student>()
               .JoinTable<School>((s1, s2) => s1.sch_id == s2.id)
               .Where(s1 => s1.id <= 3)
               .Select<V_Student>("s1.*,s2.name SchoolName")
               .ToJson();

                //select字串 轉換成Json
                var dynamic3 = db.Queryable<Student>()
               .JoinTable<School>((s1, s2) => s1.sch_id == s2.id)
               .Where(s1 => s1.id <= 3)
               .Select<V_Student>("s1.*,s2.name SchoolName")
               .ToDynamic();


                //新容器轉換函式的支援 只支援ObjToXXX和Convert.ToXXX
                var f1 = db.Queryable<InsertTest>().Select<Student>(it => new Student()
                {
                    name = it.d1.ObjToString(),
                    id = it.int1.ObjToInt() // 支援ObjToXXX 所有函式

                }).ToList();

                var f2 = db.Queryable<InsertTest>().Select<Student>(it => new Student()
                {
                    name = Convert.ToString(it.d1),//支援Convet.ToXX所有函式
                    id = it.int1.ObjToInt(),
                    sex = Convert.ToString(it.d1),

                }).ToList();

                var f3 = db.Queryable<InsertTest>()
                    .JoinTable<InsertTest>((i1, i2) => i1.id == i2.id)
                    .Select<InsertTest, Student>((i1, i2) => new Student()
                    {
                        name = Convert.ToString(i1.d1), //多表查詢例子
                        id = i1.int1.ObjToInt(),
                        sex = Convert.ToString(i2.d1),

                    }).ToList();


                //Select 外部引數用法
                var f4 = db.Queryable<InsertTest>().Where("1=1", new { id = 100 }).Select<Student>(it => new Student()
                {
                    id = "@id".ObjToInt(), //取的是 100 的值
                    name = "張三",//內部引數可以直接寫
                    sex = it.txt,
                    sch_id = it.id

                }).ToList();
                var f6 = db.Queryable<InsertTest>()
               .JoinTable<InsertTest>((i1, i2) => i1.id == i2.id)
               .Where("1=1", new { id = 100, name = "張三", isOk = true }) //外部傳參給@id
               .Select<InsertTest, Student>((i1, i2) => new Student()
               {
                   name = "@name".ObjToString(), //多表查詢例子
                   id = "@id".ObjToInt(),
                   sex = i2.txt,
                   sch_id = 1,
                   isOk = "@isOk".ObjToBool()

               }).ToList();
            }

 

 

新增/Add

 using (SqlSugarClient db = SugarDao.GetInstance())//開啟資料庫連線
            {
                Student s = new Student()
                {
                    name = "" + new Random().Next(1, int.MaxValue)
                };

                db.Insert(s); //插入一條記錄 (有主鍵也好,沒主鍵也好,有自增列也好都可以插進去)


                List<Student> list = new List<Student>()
                {
                     new Student()
                {
                     name=""+new Random().Next(1,int.MaxValue)
                },
                 new Student()
                {
                     name=""+new Random().Next(1,int.MaxValue)
                }
                };

                db.InsertRange(list); //批量插入
            }
        }
新增

 新功能SqlSugar 2.7  高效能批量插入,

using (SqlSugarClient db = SugarDao.GetInstance())//開啟資料庫連線
            {
                var list = new List<Student>()
                {
                    new Student(){ isOk=true, name="張三",  sch_id=1, sex=""},
                    new Student(){ isOk=true, name="sun",  sch_id=1, sex=""},
                    new Student(){ isOk=true, name="mama",  sch_id=1, sex="gril"}
                };
                db.SqlBulkCopy<Student>(list);
            }

 

 2.8.01設定不插入列

 

                //設定不插入
                db.DisableInsertColumns = new string[] { "sex" };//設定sex不插入
                
                Student s2 = new Student()
                {
                    name = "" + new Random().Next(1, int.MaxValue)    
                };

                db.Insert(s); //插入一

 

更新/Update

 using (var db = SugarDao.GetInstance())
            {
                //指定列更新
                db.Update<School>(new { name = "藍翔2" }, it => it.id == id);
                db.Update<School, int>(new { name = "藍翔2" }, 1, 3, 12);
                db.Update<School, string>(new { name = "藍翔2" }, new string[] { "1", "2" });

                //整個實體更新
                db.Update(new School { id = id, name = "藍翔2" });
                db.Update<School>(new School { id = id, name = "藍翔2" }, it => it.id == id);


                //設定不更新列
                db.DisableUpdateColumns = new string[] { "CreateTime" };//設定CreateTime不更新

                TestUpdateColumns updObj = new TestUpdateColumns()
                {
                    VGUID = Guid.Parse("542b5a27-6984-47c7-a8ee-359e483c8470"),
                    Name = "xx",
                    Name2 = "xx2",
                    IdentityField = 0,
                    CreateTime = null
                };

                //CreateTime將不會被更新
                db.Update(updObj);
                //以前實現這種更新需要用指定列的方式實現,現在就簡單多了。
               
            }
更新

 

刪除和假刪除/Delete And False Delete

                //刪除
                db.Delete<School, int>(10);//注意主鍵必需為實體類的第一個屬性
                db.Delete<School>(it => it.id > 100);
                //主鍵批量刪除
                db.Delete<School, string>(new string[] { "100", "101", "102" });
                //非主鍵批量刪除
                db.Delete<School, string>(it => it.name, new string[] { "" });
                db.Delete<School, int>(it => it.id, new int[] { 20, 22 });

                //假刪除
                //db.FalseDelete<school>("is_del", 100);
                //等同於 update school set is_del=1 where id in(100)
                //db.FalseDelete<school>("is_del", it=>it.id==100);
View Code

 

全域性過濾器/ Gobal Filter

這功能主要用於通用許可權設計等功能, 當有很多WHERE重複,並且動態 這時候就需要在全域性設定好過濾器介面集合,程式中使用只需要設KEY便可

    /// <summary>
    /// 過濾器
    /// </summary>
    public partial class Filter : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlSugarClient db = SugarDaoFilter.GetInstance())//開啟資料庫連線
            {
                //設定走哪個過濾器
                db.CurrentFilterKey = "role";

                //queryable
                var list = db.Queryable<Student>().ToList(); //通過全域性過濾器對需要許可權驗證的資料進行過濾
                //相當於db.Queryable<Student>().Where("id=@id",new{id=1})


                //sqlable
                var list2 = db.Sqlable().Form<Student>("s").SelectToList<Student>("*");
                //同上

                //sqlQuery
                var list3 = db.SqlQuery<Student>("select * from Student");
                //同上
            }
        }
    }
    /// <summary>
    /// 擴充套件SqlSugarClient
    /// </summary>
    public class SugarDaoFilter
    {
        //禁止例項化
        private SugarDaoFilter()
        {

        }
        /// <summary>
        /// 頁面所需要的過濾函式
        /// </summary>
        private static Dictionary<string, Func<KeyValueObj>> _filterParas = new Dictionary<string, Func<KeyValueObj>>()
        {
          { "role",()=>{
                    return new KeyValueObj(){ Key=" id=@id" , Value=new{ id=1}};
               }
          },
          { "org",()=>{ 
                    return new KeyValueObj(){ Key=" orgId=@orgId" , Value=new{ orgId=1}};
              }
          },
        };
        public static SqlSugarClient GetInstance()
        {
            string connection = System.Configuration.ConfigurationManager.ConnectionStrings[@"sqlConn"].ToString(); //這裡可以動態根據cookies或session實現多庫切換
            var reval = new SqlSugarClient(connection);
            reval.SetFilterFilterParas(_filterParas);
            return reval;
        }
    }
過濾器

行列同時過濾 2.7.07

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SqlSugar;
using Models;

namespace WebTest.Demos
{/// <summary>
    /// 過濾器 (查詢行過濾加查詢列過濾)
    /// </summary>
    public partial class Filter2 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlSugarClient db = SugarDaoFilter.GetInstance())//開啟資料庫連線
            {
                //設定走哪個過濾器
                db.CurrentFilterKey = "role";


                //queryable
                var list = db.Queryable<Student>().ToJson();


                //設定走哪個過濾器
                db.CurrentFilterKey = "org";


                //queryable
                var list2 = db.Queryable<Student>().ToJson();

            }
        }
    }
    /// <summary>
    /// 擴充套件SqlSugarClient
    /// </summary>
    public class SugarDaoFilter
    {
        //禁止例項化
        private SugarDaoFilter()
        {

        }
        /// <summary>
        /// 頁面所需要的過濾行
        /// </summary>
        private static Dictionary<string, Func<KeyValueObj>> _filterParas = new Dictionary<string, Func<KeyValueObj>>()
            {
              { "role",()=>{
                        return new KeyValueObj(){ Key=" id=@id" , Value=new{ id=1}};
                   }
              },
              { "org",()=>{
                  return new KeyValueObj() { Key = " id=@id", Value = new { id = 2 } };
                  }
              },
            };
        /// <summary>
        /// 頁面所需要的過濾列
        /// </summary>
        private static Dictionary<string, List<string>> _filterColumns = new Dictionary<string, List<string>>()
            {
              { "role",new List<string>(){"id","name"}
              },
              { "org",new List<string>(){"name"}
              },
            };
        public static SqlSugarClient GetInstance()
        {
            string connection = System.Configuration.ConfigurationManager.ConnectionStrings[@"sqlConn"].ToString(); //這裡可以動態根據cookies或session實現多庫切換
            var reval = new SqlSugarClient(connection);

            //支援sqlable和queryable
            reval.SetFilterFilterParas(_filterParas);

            //列過濾只支援queryable
            reval.SetFilterFilterParas(_filterColumns);
            return reval;
        }
    }

}
行列過濾

 

 

無參模式/No Parameter

將IsGetPageParas設為true之後頁面的引數都不需要使用  new{}來賦值

         using (SqlSugarClient db = SugarDao.GetInstance())//開啟資料庫連線
                {

                    db.IsGetPageParas = true;//使用無參模式直接將Requst中的ID傳給@id無需在程式碼中寫出來

                    var list = db.Queryable<Student>().Where("id=@id").ToList();

                    //sqlable queryable sqlquery通用

                    //獲取頁面所有引數到鍵值對
                    //var kvs= SqlSugarTool.GetParameterDictionary();

                    //以前寫法
                    //var xx = db.Queryable<Student>().Where("id=@id", new { id=Request["id"] }).ToList();
                }
無參

 

事務 /Transaction

 using (SqlSugarClient db = SugarDao.GetInstance())//開啟資料庫連線
            {
                db.IsNoLock = true;//啟用無鎖查詢
                db.CommandTimeOut = 30000;//設定超時時間
                try
                {
                    db.BeginTran();//開啟事務

                    db.CommitTran();//提交事務
                }
                catch (Exception)
                {
                    db.RollbackTran();//回滾事務
                    throw;
                }
            }
事務

 

公開函式 /Common Method

 //ToJoinSqlInVal
            var par = new string[] { "a", "c", "3" };
            var ids = par.ToJoinSqlInVal();//將陣列轉成 'a','c','3'  有防SQL隱碼攻擊處理


            //ToSqlValue
            try
            {
                var par2 = "a'";
                var newpar2 = par2.ToSqlValue();//對字串防注入處理
            }
            catch (Exception ex)
            {

                Response.Write(ex.Message);
            }

            //SqlLikeWordEncode 處理LIKE特殊字元
            var likestr = SqlSugarTool.SqlLikeWordEncode("[%%%");


            //GetParameterArray 獲取頁面引數所有引數的鍵和值
            var pars = SqlSugarTool.GetParameterArray();


            //將匿名物件轉成SqlParameter
            var par3= SqlSugarTool.GetParameters(new { id=1});
函式

 

實體生成 /Create Entity File

 using (var db = SugarDao.GetInstance())
            {
                //可以結合別名表,請看別名表的用法
                //db.SetMappingTables(mappingTableList);

                db.ClassGenerating.CreateClassFiles(db, ("e:/TestModels"), "Models");


                //批量設定別名表,可以方便生成指定格式的實體物件
                db.ClassGenerating.ForeachTables(db, tableName =>
                {
                    db.AddMappingTable(new KeyValue() { Key = "Rename_"+tableName, Value =  tableName });
                });

                //生成的檔案都Rename_開頭
                db.ClassGenerating.CreateClassFiles(db, ("e:/TestModels"), "Models",
                    null, 
                    className => { 
                      //生成檔案之後的回撥
                    }, tableName => {
                      //生成檔案之前的回撥
                    });


                //只生成student和school表的實體
                db.ClassGenerating.CreateClassFilesByTableNames(db, "e:/TestModels2", "Models", new string[] { "student", "school" });

                //根據表名生成class字串
                var str = db.ClassGenerating.TableNameToClass(db, "Student");

                var dynamicToClassStr = db.ClassGenerating.DynamicToClass(new { id = 1 }, "dyName");

                //根據SQL語句生成class字串
                var str2 = db.ClassGenerating.SqlToClass(db, "select top 1 * from Student", "student");

                //改變值(lassTemplate.ItemTemplate=XXXX)可以自定義格式
                var tempItem = ClassTemplate.ItemTemplate;//例如可以在生成的實體新增預設建構函式給指定的欄位賦預設值或者公司資訊等
                var temp = ClassTemplate.Template;
                var temSummary = ClassTemplate.ClassFieldSummaryTemplate;


                //設定新格式模板
                //主鍵Guid.New(),
                //CreateTime為DateTime.Now 
                //IsRemove=0
                //UpdateTime為DateTime.Now 
                ClassTemplate.Template = "using System;\r\nusing System.Linq;\r\nusing System.Text;\r\n\r\nnamespace $namespace\r\n{\r\n    public class $className\r\n    {\r\n        public $className() \r\n        { \r\n            this.CreateTime = DateTime.Now;\r\n            this.  = 0;\r\n            this.UpdateTime=DateTime.Now;\r\n            this.$primaryKeyName=Guid.NewGuid().ToString(\"N\").ToUpper();\r\n        }\r\n        $foreach\r\n    }\r\n}\r\n";

                //新格式的實體字串
                var str3 = db.ClassGenerating.TableNameToClass(db, "Student");

            }
View Code

 

T4模版

詳細教程:

http://www.cnblogs.com/sunkaixuan/p/5751503.html

 

自定義生成實體的格式

例如給每個實體 指定欄位新增預設值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebTest.Dao;
using SqlSugar;

namespace WebTest.Demos
{
    public partial class CreateModelFile2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //自定義實體模板引擎模組
            ClassTemplate.Template = "using System;\r\nusing System.Linq;\r\nusing System.Text;\r\n\r\nnamespace $namespace\r\n{\r\n    public class $className\r\n    {\r\n        public $className() \r\n        { \r\n            this.CreateTime = DateTime.Now;\r\n            this.IsRemove = 0;\r\n            this.UpdateTime=DateTime.Now;\r\n            this.$primaryKeyName=Guid.NewGuid().ToString(\"N\").ToUpper();\r\n        }\r\n        $foreach\r\n    }\r\n}\r\n";
            using (var db = SugarDao.GetInstance())
            {
                db.ClassGenerating.CreateClassFiles(db, "e:/TestModel", "Models");
                //生成的Model帶建構函式並且賦了預設值 ,如下注釋

            }
        }
        //public class InsertTest
        //{
        //    public InsertTest()
        //    {
        //        this.CreateTime = DateTime.Now;
        //        this.IsRemove = 0;
        //        this.UpdateTime = DateTime.Now;
        //        this.id = Guid.NewGuid().ToString("N").ToUpper();
        //    }

        //    /// <summary>
        //    /// Desc:- 
        //    /// Default:- 
        //    /// Nullable:False 
        //    /// </summary>
        //    public int id { get; set; }

        //    /// <summary>
        //    /// Desc:- 
        //    /// Default:- 
        //    /// Nullable:True 
        //    /// </summary>
        //    public string v1 { get; set; }

        //    /// <summary>
        //    /// Desc:- 
        //    /// Default:- 
        //    /// Nullable:True 
        //    /// </summary>
        //    public string v2 { get; set; }

        //    /// <summary>
        //    /// Desc:- 
        //    /// Default:- 
        //    /// Nullable:True 
        //    /// </summary>
        //    public string v3 { get; set; }

        //    /// <summary>
        //    /// Desc:- 
        //    /// Default:- 
        //    /// Nullable:True 
        //    /// </summary>
        //    public int? int1 { get; set; }

        //    /// <summary>
        //    /// Desc:- 
        //    /// Default:- 
        //    /// Nullable:True 
        //    /// </summary>
        //    public DateTime? d1 { get; set; }

        //    /// <summary>
        //    /// Desc:- 
        //    /// Default:- 
        //    /// Nullable:True 
        //    /// </summary>
        //    public string txt { get; set; }

        //}
    }
}
View Code

 

 

別名表/Rename table name

SqlSugar走的是POCO路線,並不需要在Model裡面新增任何特性

    /// <summary>
    /// 使用別名表功能
    /// </summary>
    public partial class Rename : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlSugarClient db = SugarFactory.GetInstance())
            {
                var list = db.Queryable<V_Student>().ToList(); //使用別名表
            }
        }
    }
    /// <summary>
    /// 全域性配置類
    /// </summary>
    public class SugarConfigs
    {
        //key類名 value表名
        public static List<KeyValue> MpList = new List<KeyValue>(){
                new KeyValue(){ Key="FormAttr", Value="Flow_FormAttr"},
                new KeyValue(){ Key="Student3", Value="Student"},
                new KeyValue(){ Key="V_Student", Value="Student"}
                };
    }
    /// <summary>
    /// SqlSugar例項工廠
    /// </summary>
    public class SugarFactory
    {

        //禁止例項化
        private SugarFactory()
        {

        }
        public static SqlSugarClient GetInstance()
        {
            string connection = System.Configuration.ConfigurationManager.ConnectionStrings[@"sqlConn"].ToString(); //這裡可以動態根據cookies或session實現多庫切換
            var db = new SqlSugarClient(connection);
            db.SetMappingTables(SugarConfigs.MpList);//設定關聯表 (引用地址賦值,每次賦值都只是儲存一個記憶體地址)
            return db;
        }
    }

  

 

列舉支援

        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlSugarClient db = SugarDao.GetInstance())
            {
                var stuList= db.Queryable<Student>().ToList();
                db.Insert<Student>(new Student() { sch_id = SchoolEnum.北大青鳥 });
                db.Update<Student>(new Student() { sch_id = SchoolEnum.it清華, id = 11 });
                var stuList2 = db.Queryable<Student>().Where(it => it.sch_id == SchoolEnum.全智).ToList();
            }
        }


        public class Student
        {

            /// <summary>
            /// 說明:- 
            /// 預設:- 
            /// 可空:False 
            /// </summary>
              public int id { get; set; }

            /// <summary>
            /// 說明:- 
            /// 預設:- 
            /// 可空:True 
            /// </summary>
            public string name { get; set; }

            /// <summary>
            /// 說明:- 
            /// 預設:- 
            /// 可空:False 
            /// </summary>
            public SchoolEnum sch_id { get; set; }

            /// <summary>
            /// 說明:- 
            /// 預設:- 
            /// 可空:True 
            /// </summary>
            public string sex { get; set; }

            /// <summary>
            /// 說明:- 
            /// 預設:- 
            /// 可空:False 
            /// </summary>
            public bool isOk { get; set; }

        }

        public enum SchoolEnum
        {
            北大青鳥 = 1,
            it清華 = 2,
            全智=3
        }
View Code

 

 

排除非資料庫列 SqlSugar2.7新功能

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SqlSugar;
using WebTest.Dao;
using WebTest.TestLib;

namespace WebTest.Demos
{
    public partial class IgnoreErrorColumns : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlSugarClient db = SugarDao.GetInstance())
            {
       
                //設定別名表具體例子看rename.aspx,不是該例子的重點
                db.SetMappingTables(new List<KeyValue>() { new KeyValue() { Key = "MyStudent", Value = "Student" }, });
                 
//重點來了
//資料庫並沒有appendField和appendField2二個欄位,設定該屬性後將插入可以正常使用 db.IsIgnoreErrorColumns = true;//自動排除非資料庫列 update也一樣 db.Insert<MyStudent>(new MyStudent() { name = "張三" }); //將實體MyStudent插入Student表 } } } /// <summary> /// 繼承了學生表 /// </summary> public class MyStudent : Student { /// <summary> /// 這兩個欄位Student表並不存在 /// </summary> public string appendField { get; set; } public string appendField2 { get; set; } } }

 

智慧提示配置

http://www.cnblogs.com/sunkaixuan/p/5851425.html

 

多庫平行計算功能

 using (CloudClient db = CloudDao.GetInstance())
            {
                db.PageMaxHandleNumber = 1500;
                using (CommittableTransaction trans = new CommittableTransaction())//啟用分散式事務
                {


                    db.Tran = trans;

                    /*** 增、刪、改 ***/

                    //根據配置的百分比,隨機插入到某個節點庫
                    var s = new student()
                    {
                        createTime = DateTime.Now,
                        id = Guid.NewGuid(),
                        name = Guid.NewGuid() + ""
                    };
                    //db.Insert<student>(s, false/*false表示不是自增列*/); //資料庫設計主鍵為GUID為佳多庫計算不會衝突



                    ////併發請求所有節點找出這條資料更新
                    //s.name = "改11";
                    //db.Update<student>(s, it => it.id == s.id);//根據表達示更新


                    //db.Update<student, Guid>(s, s.id);//根據主鍵更新

                    //db.Update<student, Guid>(s, new Guid[] { s.id });//根據主鍵陣列更新



                    ////併發請求所有節點找出這條資料刪除
                    //db.Delete<student>(it => it.id == s.id);


                    trans.Commit();
                }

                db.TranDispose();


                /*** 使用Taskable實現雲端計算 ***/


                //多執行緒請求所有資料庫節點,獲取彙總結果
                var taskDataTable = db.Taskable<DataTable>("SELECT max(NUM) FROM STUDENT").Tasks;
                foreach (var dr in taskDataTable)//遍歷所有節點資料
                {
                    var dt = dr.Result.DataTable;//每個節點的資料 型別為DataTable
                    var connectionName = dr.Result.ConnectionString;
                }

                //多執行緒請求所有資料庫節點,獲取彙總結果
                var taskInt = db.Taskable<int>("SELECT max(NUM) FROM STUDENT").Tasks;
                foreach (var dr in taskInt)//遍歷所有節點資料
                {
                    var dt = dr.Result.Value;//獲取單個值
                    var connectionName = dr.Result.ConnectionString;
                }

                //多執行緒請求所有資料庫節點,獲取彙總結果
                var taskEntity = db.Taskable<student>("SELECT top 100 * FROM STUDENT").Tasks;
                foreach (var dr in taskEntity)//遍歷所有節點資料
                {
                    var dt = dr.Result.Entities;//獲取實體集合
                    var connectionName = dr.Result.ConnectionString;
                }

                // //Taskable實現分組查詢
                // var groupList = db.Taskable<DataTable>("SELECT name,COUNT(*) AS [count],AVG(num) as num FROM STUDENT WHERE ID IS NOT NULL  GROUP BY NAME ")
                //     .Tasks
                //     .SelectMany(it => it.Result.DataTable.AsEnumerable())
                //     .Select(dr => new { num = Convert.ToInt32(dr["NUM"]), name = dr["NAME"].ToString(), count = Convert.ToInt32(dr["COUNT"]) })
                //     .GroupBy(dr => dr.name).Select(dt => new { name = dt.First().name, count = dt.Sum(dtItem => dtItem.count), num = dt.Sum(dtItem => dtItem.num) / dt.Sum(dtItem => dtItem.count) }).ToList();


                // //輸出結果
                // foreach (var it in groupList)
                // {
                //     var num = it.num;
                //     var name = it.name;
                //     var count = it.count;
                // }


                // //簡化
                // var groupList2 = db.Taskable<DataTable>("SELECT NAME,COUNT(*) AS [COUNT],AVG(NUM) as NUM FROM STUDENT WHERE ID IS NOT NULL  GROUP BY NAME ")
                //.MergeTable()//將結果集合併到一個集合
                //.Select(dr => new { num = Convert.ToInt32(dr["NUM"]), name = dr["NAME"].ToString(), count = Convert.ToInt32(dr["COUNT"]) })
                //.GroupBy(dr => dr.name).Select(dt => new { name = dt.First().name, count = dt.Sum(dtItem => dtItem.count), num = dt.Sum(dtItem => dtItem.num) / dt.Sum(dtItem => dtItem.count) }).ToList();

                // //再簡化
                // List<V_Student> groupList3 = db.Taskable<V_Student>("SELECT name,COUNT(*) AS [count],AVG(num) as num FROM STUDENT WHERE ID IS NOT NULL  GROUP BY NAME ")
                //.MergeEntities()//將結果集合併到一個集合
                //.GroupBy(dr => dr.name).Select(dt => new V_Student { name = dt.First().name, count = dt.Sum(dtItem => dtItem.count), num = dt.Sum(dtItem => dtItem.num) / dt.Sum(dtItem => dtItem.count) }).ToList();



                //更多簡化函式
                int maxValue = db.Taskable<int>("SELECT max(NUM) FROM STUDENT").Max();//求出所有節點的最大值
                int minValue = db.Taskable<int>("SELECT min(NUM) FROM STUDENT").Min();//求出所有節點的最小值
                var dataCount = db.Taskable<int>("SELECT count(1) FROM STUDENT").Count();//求出所有節點資料
                // var avg = db.TaskableWithCount<int>("SELECT avg(num)", " FROM STUDENT").Avg();
                var all = db.Taskable<student>("select * from student where Contains(name,@name)"/*使用contains需要建全文索引*/, new { name = "張三" }).ToList();//獲取所有節點name為張三的資料,轉為list

                var dnSingle = DateTime.Now;
                var data = db.Taskable<student>("select * from student where id=@id", new { id = id }).ToSingle();//從所有節點中查詢一條記錄
                var timeSingle = (DateTime.Now - dnSingle).TotalSeconds;

                var dn = DateTime.Now;
                //單列排序
                //  var list = db.TaskableWithPage<student>("id", "select * from student    "/*使用contains需要建全文索引*/, 2160, 25, ref pageCount, "num", OrderByType.desc, new { name = "\"*李*\"" });
                var time = (DateTime.Now - dn).TotalSeconds;

                //多組排序 order by num,time
                var dn2 = DateTime.Now;
                var listMultipleOrderBy = db.TaskableWithPage<student>("id", "select * from student   "/*使用contains需要建全文索引*/, 5000, 25, ref pageCount, new List<OrderByDictionary>() { 
                     new   OrderByDictionary(){ OrderByField="num", OrderByType=OrderByType.asc},
                     //       new   OrderByDictionary(){ OrderByField="createTime", OrderByType=OrderByType.desc},
                   //  new OrderByDictionary(){ OrderByField="createTime", OrderByType=OrderByType.asc}
                }, new { name = "\"*小*\"" });
                var time2 = (DateTime.Now - dn2).TotalSeconds;


            }
多庫模式
 /// <summary>
        /// 測試類
        /// </summary>
        public class student
        {
            public Guid id { get; set; }
            public string name { get; set; }
            public DateTime createTime { get; set; }
            public int num { get; set; }
        }
        /// <summary>
        /// 獲取資料庫連線物件
        /// </summary>
        public class CloudDao
        {
            private CloudDao() { }
            public static CloudClient GetInstance()
            {
                return new CloudClient(new List<CloudConnectionConfig>() { 
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c1"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c2"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c3"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c4"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c5"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c6"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c7"].ToString(), Rate=1},
                 new CloudConnectionConfig(){  ConnectionString=ConfigurationManager.ConnectionStrings["c8"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c9"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c10"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c15"].ToString(), Rate=1},
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c16"].ToString(), Rate=1},              
                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["c17"].ToString(), Rate=1},
                //new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["cy1"].ToString(), Rate=1},
                //   new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["cy2"].ToString(), Rate=1},
                //    new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["cy3"].ToString(), Rate=1},
                //                      new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["zq1"].ToString(), Rate=1},
                //   new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["zq2"].ToString(), Rate=1},
                //    new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["zq3"].ToString(), Rate=1},
                //            new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["qp1"].ToString(), Rate=1},
                //   new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["qp2"].ToString(), Rate=1},
                //    new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["qp3"].ToString(), Rate=1},
                //                 new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wy1"].ToString(), Rate=1},
                //   new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wy2"].ToString(), Rate=1},
                //    new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wy3"].ToString(), Rate=1},
                //                                   new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wwf1"].ToString(), Rate=1},
                //   new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wwf2"].ToString(), Rate=1},
                //    new CloudConnectionConfig(){ ConnectionString=ConfigurationManager.ConnectionStrings["wwf3"].ToString(), Rate=1},


            });
            }
        }
多庫配置

 

3、效能/Performance

 

 

 GITHUB下載地址:

MSSQL .NET 4.0+

https://github.com/sunkaixuan/SqlSugar 

MSSQL .NET Core 版本

https://github.com/sunkaixuan/ASP_NET_CORE_ORM_SqlSugar

 

 Sqlite .net4.0+

https://github.com/sunkaixuan/SqliteSugar

 

MYSQL .NET 4.0+

http://www.cnblogs.com/sunkaixuan/p/5747259.html

 

ORACLE.NET 4.0+

https://github.com/sunkaixuan/OracleSugar

 ORACLE CORE ,MYSQL CORE,SQLITE  CORE 待開發

 

 

 

技術討論群: 225982985

 

  

相關文章