OracleSugar ORM框架的誕生,程式碼開源

孫凱旋發表於2016-09-14

 經過四天的努力終於將SqlSugar ORM 成功支援ORACLE資料庫 

 

優點:

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

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

3、支援.net Core

4、支援多庫平行計算

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

6、無需任何配置 ,還你一個乾淨的model

 

 

 

 

2、功能介紹/Product function introduction

 

查詢/Search

 

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

 

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

 

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

 

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

   //查詢所有
                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();

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

                //上一句的簡化寫法,同樣取10-20條
                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 ").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<STUDENT, 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<STUDENT, 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<SexTotal> list9 = db.Queryable<STUDENT>().Where(c => c.ID < 20).GroupBy(it => it.SEX).Select<STUDENT, SexTotal>("SEX,count(*) COUNT").ToList();
                List<SexTotal> list10 = db.Queryable<STUDENT>().Where(c => c.ID < 20).GroupBy("sex").Select<STUDENT, SexTotal>("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<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) //預設left join
                .Where<STUDENT, 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<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) //預設left join
                    //如果要用inner join這麼寫
                    //.JoinTable<Student, School>((s1, s2) => s1.sch_id == s2.id  ,JoinType.INNER)
                .Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > 1)
                .OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.NAME)
                .Skip(10)
                .Take(20)
                .Select("s1.*,s2.name as schName")
                .ToDynamic();

                //3表查詢並分頁
                var jList3 = db.Queryable<STUDENT>()
               .JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join  School s2  on s1.id=s2.id
               .JoinTable<STUDENT, SCHOOL>((s1, s3) => s1.SCH_ID == s3.ID) // left join  School s3  on s1.id=s3.id
               .Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > 1)  // where s1.id>1
               .Where<STUDENT>(s1 => s1.ID > 0)
               .OrderBy<STUDENT, 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<classNew> jList4 = db.Queryable<STUDENT>()
                 .JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join  School s2  on s1.id=s2.id
                 .JoinTable<STUDENT, SCHOOL, AREA>((s1, s2, a1) => a1.ID == s2.AREAID)// left join  Area a1  on a1.id=s2.AreaId
                 .Select<STUDENT, SCHOOL, AREA, classNew>((s1, s2, a1) => new classNew { NEWID = s1.ID, STUDENTNAME = s1.NAME, SCHOOLNAME = s2.NAME, AREANAME = a1.NAME }).ToList();




                //最多支援5表查詢,太過複雜的建議用Sqlable或者SqlQuery,我們的Queryable只適合輕量級的查詢





                //拼接
                var queryable = db.Queryable<STUDENT>().Where(it => true);
                if (maxId.ObjToInt() == 1)
                {
                    queryable.Where(it => it.ID == 1);
                }
                else
                {
                    queryable.Where(it => it.ID == 2);
                }
                var listJoin = queryable.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 convert4 = db.Queryable<STUDENT>().Where(c => DateTime.Now > DateTime.Now).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();

 

 

 

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   id from Student where rownum=1").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   id,name from Student where rownum=1").SingleOrDefault();

                //儲存過程
                //var spResult = db.SqlQuery<SCHOOL>(@"begin exec sp_school (:p1,:p2); end;", new { p1 = 1, p2 = 2 });

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

 

 

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

 //多表查詢
                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("s.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 as id from dual )" /*這裡面寫子查詢都可以*/)
                    .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  id from school where rownum<10)");//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);
View Code

 

 

4、新容器轉換 / To new container

 using (SqlSugarClient db = SugarDao.GetInstance())
            {
                var list2 = db.Queryable<STUDENT>().Where(c => c.ID < 10).Select(c => new classNew { NEWID = c.ID, NEWNAME = c.NAME, XX_NAME = c.NAME }).ToList();//不支援匿名類轉換,也不建議使用

                var list3 = db.Queryable<STUDENT>().Where(c => c.ID < 10).Select(c => new { newid = c.ID, newname = c.NAME, xx_name = c.NAME }).ToDynamic();//匿名類轉換

                var list4 = db.Queryable<STUDENT>().Where(c => c.ID < 10).Select("id as newid, name as newname ,name as xx_name").ToDynamic();//匿名類轉換

                var jList1 = db.Queryable<STUDENT>()
                 .JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join  School s2  on s1.id=s2.id
                 .Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > 1)  // where s1.id>1
                 .OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多個order可以  .oderBy().orderby 疊加 
                 .Skip(1)
                 .Take(2)
                 .Select<STUDENT, SCHOOL, classNew>((s1, s2) => new classNew() { NEWID = s1.ID, NEWNAME = s2.NAME, XX_NAME = s1.NAME })//select目前只支援這種寫法
                 .ToList();

                var jList2 = db.Queryable<STUDENT>()
                .JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join  School s2  on s1.id=s2.id
                .Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > 1)  // where s1.id>1
                .OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多個order可以  .oderBy().orderby 疊加 
                .Skip(1)
                .Take(2)
                .Select<STUDENT, SCHOOL, classNew>((s1, s2) => new classNew() { NEWID = s1.ID, NEWNAME = s1.NAME, XX_NAME = s1.NAME })//select目前只支援這種寫法
                .ToDynamic();


                var jList3 = db.Queryable<STUDENT>()
                .JoinTable<STUDENT, SCHOOL>((s1, s2) => s1.SCH_ID == s2.ID) // left join  School s2  on s1.id=s2.id
                .Where<STUDENT, SCHOOL>((s1, s2) => s1.ID > 1)  // where s1.id>1
                .OrderBy<STUDENT, SCHOOL>((s1, s2) => s1.ID) //order by s1.id 多個order可以  .oderBy().orderby 疊加 
                .Skip(1)
                .Take(2)
                .Select<STUDENT, classNew>(s1 => new classNew() { NEWID = s1.ID, NEWNAME = s1.NAME, XX_NAME = s1.NAME })//select目前只支援這種寫法
                .ToDynamic();
            }

 

 

 

新增/Add

            //設定序列,程式起動時設定一次便可
            OracleConfig.SequenceMapping = new List<PubModel.SequenceModel>()
            {
                  new PubModel.SequenceModel(){ ColumnName="ID", TableName="STUDENT", Value="SEQ_D"} 
            };
            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); //批量插入
            }

 

 

更新/Update

            int id = 11;
using (var db = SugarDao.GetInstance())
            {
                //指定列更新
                db.Update<SCHOOL>(new { name = "藍翔14" }, it => it.ID == 14);
                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 == id);

   

                //支援欄位指定列更新,適合動態許可權
                var dic =new Dictionary<string, string>();
                dic.Add("name","第十三條");
                dic.Add("areaId", "1");
                db.Update<SCHOOL,int>(dic, 13);
                db.Update<SCHOOL>(dic, it => it.ID == 13);



                //整個實體更新
                db.Update(new SCHOOL { ID = 16, NAME = "藍翔16", AREAID=1 });
                db.Update<SCHOOL>(new SCHOOL { ID = id, NAME = "藍翔18", AREAID=2 }, it => it.ID == 18);
                db.Update<SCHOOL>(new SCHOOL() { ID = 11, NAME = "xx" });

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

                TESTUPDATECOLUMNS updObj = new TESTUPDATECOLUMNS()
                {
                    VGUID = "542b5a27-6984-47c7-a8ee-359e483c8470",
                    NAME = "xx",
                    NAME2 = "xx2",
                    IDENTITYFIELD = 1,
                    CREATETIME = null
                };

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

 

 

刪除和假刪除/Delete And False Delete

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

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

 

全域性過濾器/ Gobal Filter

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

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

namespace WebTest.Demo
{
    /// <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().From<STUDENT>("s").SelectToList<STUDENT>("*");
                //同上

                //sqlQuery
                var list3 = db.SqlQuery<STUDENT>("select * from Student WHERE 1=1");
                //同上
            }
        }
    }
    /// <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;
        }
    }
}
View Code

 

行列同時過濾 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 OracleSugar;
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;
        }
    }

}
View Code

 

 

 

 

 

無參模式/No Parameter

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

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

namespace WebTest.Demo
{
    /// <summary>
    /// 偷懶我就不給引數賦值
    /// </summary>
    public partial class NoParameter : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                

                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();
                }
            }
            catch (Exception)
            {
                
                throw new Exception("請在當前頁面URL地址後面加上引數?id=1");
            }
        }
    }
}
View Code

 

 

事務 /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

          //根據當前資料庫生成所有表的實體類檔案 (引數:SqlSugarClient ,檔案目錄,名稱空間)
                db.ClassGenerating.CreateClassFiles(db, Server.MapPath("~/Models"), "Models");
                //根據表名生成實體類檔案
                //db.ClassGenerating.CreateClassFilesByTableNames(db, Server.MapPath("~/Models"), "Models" , "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 * from Student where rownum=1", "student");



                //改變值(lassTemplate.ItemTemplate=XXXX)可以自定義格式
                 var tempItem=ClassTemplate.ItemTemplate;
                 var temp=ClassTemplate.Template ;

 

T4模版

詳細教程:

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

 

別名表/Rename table name

                //-----單個-------//
                var list = db.Queryable<V_Student>("Student").ToList();//查詢的是 select * from student 而我的實體名稱為V_Student




                //-----全域性多個設定-------//

                //設定 Mapping Table 如果沒這方面需求可以傳NULL
                List<KeyValue> mappingTableList = new List<KeyValue>(){
                new KeyValue(){ Key="FormAttr", Value="Flow_FormAttr"},
                new KeyValue(){ Key="Student3", Value="Student"}
                };
                db.SetMappingTables(mappingTableList);
別名表

 

排除非資料庫列 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 ,MYSQL CORE,SQLITE  CORE

待開發

 

 

 

技術討論群: 225982985

 

  

相關文章