程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> 開源ORM框架 SqlSugar 3.0的巨大變化,ormsqlsugar

開源ORM框架 SqlSugar 3.0的巨大變化,ormsqlsugar

編輯:關於.NET

開源ORM框架 SqlSugar 3.0的巨大變化,ormsqlsugar


SqlSugar從1.0版本一直更新到3.0 ,使用該 ORM的人也越來越多,需求也越來越多,提出的需求和大家給我的建議的也都盡力滿足。

並且 重構了EMIT和拉姆達解析,添加了無數的新功能,重新整了的GIT HUB上的DEMO,重新整理了所有注釋。

 

完全基於SqlSugar的開源CMS http://www.baisoft.org/ 作者已經完成了後台並且將會開源。

SqlSugar 3.0 即將發布 現在版本 2.99

 

優點:

SqlSugar 是一款小巧,並且功能齊全的ORM,並不需要像Dapper一樣依賴第三方擴展

SqlSugar 語法易用簡單 ,有漂亮的拉姆達語法,也支持Dapper SQL和ADO.NET的所有功能

SqlSugar 性能達到原生水准,遠超 Dapper和EF CORE。

SqlSugar 支持.NET CORE , 多個數據庫

SqlSugar 體積小巧只有150K是EF的30分之1 ,NUGET直接可以下載

 

特色功能

SqlbulkCopy和SqlbulkReplace 這兩個函數能夠處理海量數據插入和更新 ,也是眾多ORM沒有集成的功能之一 

SQL日志功能 可以方便的對SQL進行監控和寫入日志

全局過濾器  例如我都有IsDeleted來標識是否刪 除, 這樣我每查一個表就 要加一個WHERE條件 ,有了全局過濾器就變成非常方便

T4+實體生成 可以自定義實體格式 並且可以能過T4模版快速生成實體文件

POCO設計   實體類沒有任何屬性完全原生態

 

1、使用拉姆達進行查詢

                //---------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 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 = "   我 有空格, ";
                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 => 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、使用原生SQL查詢

                //轉成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、SQL高級拼接器寫法

 using (var db = SugarDao.GetInstance())
            {
                //---------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
                   .OrderBy("id")
                   .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、更新

                //指定列更新
                db.Update<School>(new { name = "藍翔14" }, it => it.id == 14); //只更新name列
                db.Update<School, int>(new { name = "藍翔11 23 12", areaId = 2 }, 11, 23, 12);
                db.Update<School, string>(new { name = "藍翔2" }, new string[] { "11", "21" });
                db.Update<School>(new { name = "藍翔2" }, it => it.id == 100);



                //支持字典更新,適合動態權限
                var dic = new Dictionary<string, string>();
                dic.Add("name", "第十三條");
                dic.Add("areaId", "1");
                db.Update<School, int>(dic, 13);


                //整個實體更新
                db.Update(new School { id = 16, name = "藍翔16", AreaId = 1 });
                db.Update<School>(new School { id = 12, name = "藍翔12", AreaId = 2 }, it => it.id == 18);
                db.Update<School>(new School() { id = 11, name = "青鳥11" });

                //設置不更新列
                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);
                //以前實現這種更新需要用指定列的方式實現,現在就簡單多了。



                //批量更新   數據量小時建議使用
                var updateResult = db.UpdateRange(GetUpdateList());

                //批量更新  數據量大時建議使用
                var updateResult2 = db.SqlBulkReplace(GetUpdateList2());

 

5、刪除和狀態刪除

               //刪除
                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);

 

6、插入

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


                db.InsertRange(GetInsertList()); //批量插入 支持(別名表等功能)


                db.SqlBulkCopy(GetInsertList()); //批量插入 適合海量數據插入,要求實體與數據庫一致,不支持(別名表、排除列等功能)



                //設置不插入列
                db.DisableInsertColumns = new string[] { "sex" };//sex列將不會插入值
                Student s = new Student()
                {
                    name = "張" + new Random().Next(1, int.MaxValue),
                    sex = "gril"
                };
                var id = db.Insert(s); //插入
                //查詢剛插入的sex是否有值
                var sex = db.Queryable<Student>().Single(it => it.id == id.ObjToInt()).sex;//無值
                var name = db.Queryable<Student>().Single(it => it.id == id.ObjToInt()).name;//有值

 

7、枚舉支持

  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();

 

8、實體生成加T4

//可以結合別名表,請看別名表的用法 //db.SetMappingTables(mappingTableList); db.ClassGenerating.CreateClassFiles(db, ("e:/TestModels"), "Models"); //只生成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; //設置新格式模板 //主鍵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

 

 

9、ADO.NET

var r1 = db.GetDataTable("select * from student"); var r2 = db.GetSingle<Student>("select top 1 * from student"); var r3 = db.GetScalar("select count(1) from student"); var r4 = db.GetReader("select count(1) from student"); r4.Dispose(); var r5 = db.GetString("select top 1 name from student"); var r6 = db.ExecuteCommand("select 1"); //參數支持 var p1 = db.GetDataTable("select * from student where id=@id", new {id=1 }); var p2 = db.GetDataTable("select * from student where id=@id", new Dictionary<string, object>() { { "id", "1" } });//目前只支持 Dictionary<string, object>和Dictionary<string, string> var p3 = db.GetDataTable("select * from student where id=@id", new SqlParameter("@id",1) ); View Code

 

10、日志記錄功能

//日志記錄功能 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; } } } } View Code

 

11、別名表功能

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 MappingTable : IDemos { public void Init() { Console.WriteLine("啟動MappingTable.Init"); //單個設置 using (var db = SugarDao.GetInstance()) { var list = db.Queryable<V_Student>("Student").ToList();//查詢的是 select * from student 而我的實體名稱為V_Student } //全局設置 using (var db = SugarFactory.GetInstance()) { var list = db.Queryable<V_Student>().ToList();//查詢的是 select * from student 而我的實體名稱為V_Student } } /// <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 = SugarDao.ConnectionString; //這裡可以動態根據cookies或session實現多庫切換 var db = new SqlSugarClient(connection); db.SetMappingTables(SugarConfigs.MpList);//設置關聯表 (引用地址賦值,每次賦值都只是存儲一個內存地址) return db; } } } } View Code

 

12、行列過濾

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 Filter2 : IDemos { public void Init() { Console.WriteLine("啟動Filter2.Init"); using (SqlSugarClient db = SugarDaoFilter.GetInstance())//開啟數據庫連接 { //設置走哪個過濾器 db.CurrentFilterKey = "role1"; //queryable var list = db.Queryable<Student>().ToJson(); //where id=1 , 可以查看id和name //設置走哪個過濾器 db.CurrentFilterKey = "role2"; //queryable var list2 = db.Queryable<Student>().ToJson(); //where id=2 , 可以查看name } } /// <summary> /// 擴展SqlSugarClient /// </summary> public class SugarDaoFilter { //禁止實例化 private SugarDaoFilter() { } /// <summary> /// 頁面所需要的過濾行 /// </summary> private static Dictionary<string, Func<KeyValueObj>> _filterParas = new Dictionary<string, Func<KeyValueObj>>() { { "role1",()=>{ return new KeyValueObj(){ Key=" id=@id" , Value=new{ id=1}}; } }, { "role2",()=>{ return new KeyValueObj() { Key = " id=@id", Value = new { id = 2 } }; } }, }; /// <summary> /// 頁面所需要的過濾列 /// </summary> private static Dictionary<string, List<string>> _filterColumns = new Dictionary<string, List<string>>() { { "role1",new List<string>(){"id","name"} }, { "role2",new List<string>(){"name"} }, }; public static SqlSugarClient GetInstance() { string connection = SugarDao.ConnectionString; //這裡可以動態根據cookies或session實現多庫切換 var reval = new SqlSugarClient(connection); //支持sqlable和queryable reval.SetFilterFilterParas(_filterParas); //列過濾只支持queryable reval.SetFilterFilterParas(_filterColumns); return reval; } } } } View Code

 

13、自動排除非數據庫列

//排除錯誤列 public class IgnoreErrorColumns : IDemos { public void Init() { Console.WriteLine("啟動IgnoreErrorColumns.Init"); using (var db = SugarDao.GetInstance()) { db.IsIgnoreErrorColumns = true; //Student表並沒有 AreaName var id= db.Insert<STUDENT>(new STUDENT() { name = "張三", AreaName = "北大" }); db.Update<STUDENT>(new STUDENT() { id=id.ObjToInt() ,name = "張三2", AreaName = "北大" }); } } public class STUDENT { /// <summary> /// Desc:- /// Default:- /// Nullable:False /// </summary> public int id { get; set; } /// <summary> /// Desc:- /// Default:- /// Nullable:True /// </summary> public string name { get; set; } /// <summary> /// Desc:學校ID /// Default:- /// Nullable:True /// </summary> public int? sch_id { get; set; } /// <summary> /// Desc:- /// Default:- /// Nullable:True /// </summary> public string sex { get; set; } /// <summary> /// Desc:- /// Default:- /// Nullable:True /// </summary> public Boolean? isOk { get; set; } public string SchoolName { get; set; } public string AreaName { get; set; } public string SubjectName { get; set; } } } View Code

 

14、事務

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 Tran : IDemos { public void Init() { Console.WriteLine("啟動Tran.Init"); using (SqlSugarClient db = SugarDao.GetInstance())//開啟數據庫連接 { db.IsNoLock = true;//啟用無鎖查詢 db.CommandTimeOut = 30000;//設置超時時間 try { db.BeginTran();//開啟事務 //db.BeginTran(IsolationLevel.ReadCommitted);+3重載可以設置事世隔離級別 db.CommitTran();//提交事務 } catch (Exception) { db.RollbackTran();//回滾事務 throw; } } } } } View Code

 

15、流水號功能

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 SerialNumber : IDemos { public void Init() { Console.WriteLine("啟動SerialNumber.Init"); using (SqlSugarClient db = SugarFactory.GetInstance())//開啟數據庫連接 { var dientityValue = db.Insert<Student>(new Student() { }); var name = db.Queryable<Student>().Single(it => it.id == dientityValue.ObjToInt()).name; Console.WriteLine(name); var dientityValue2 = db.Insert<School>(new School() { }); var name2 = db.Queryable<School>().Single(it => it.id == dientityValue2.ObjToInt()).name; Console.WriteLine(name2); ; } } /// <summary> /// 全局配置類 /// </summary> public class SugarConfigs { public static List<PubModel.SerialNumber> NumList = new List<PubModel.SerialNumber>(){ new PubModel.SerialNumber(){TableName="Student", FieldName="name", GetNumFunc=()=>{ //GetNumFunc在沒有事中使用 return "stud-"+DateTime.Now.ToString("yyyy-MM-dd"); }}, new PubModel.SerialNumber(){TableName="School", FieldName="name", GetNumFuncWithDb=db=>{ //事務中請使用GetNumFuncWithDb保證同一個DB對象,不然會出現死鎖 return "ch-"+DateTime.Now.ToString("syyyy-MM-dd"); }} }; } /// <summary> /// SqlSugar實例工廠 /// </summary> public class SugarFactory { //禁止實例化 private SugarFactory() { } public static SqlSugarClient GetInstance() { string connection = SugarDao.ConnectionString; //這裡可以動態根據cookies或session實現多庫切換 var db = new SqlSugarClient(connection); db.SetSerialNumber(SugarConfigs.NumList);//設置流水號 return db; } } } } View Code

 

16、多庫並行計算功能

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SqlSugar; using System.Configuration; using System.Data; using System.Threading.Tasks; using System.Transactions; using System.Threading; namespace WebTest.Demo { /// <summary> /// /*******************************************************************分布式計算 demo**************************************************************/ /// </summary> public partial class Cloud : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var id = Guid.Parse("4FC950EC-7C23-480F-9545-443EBDCA32E9"); int pageCount = 0; 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}, }); } } } } View Code

 

 

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 待開發

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved