[開源].NET CORE與MySql更配, MySqlSugar ORM框架 3.x

来源:http://www.cnblogs.com/sunkaixuan/archive/2016/10/22/5987308.html
-Advertisement-
Play Games

MySqlSugar 3.X API 作為支持.NET CORE 為數不多的ORM之一,除了具有優越的性能外,還擁有強大的功能,不只是滿足你的增,刪,查和改。實質上擁有更多你想像不到的功能,當你需要實現某個功能時會發現有這個功能太棒了。 所有版本 ASP.NET 4.0+ MSSQL https:/ ...


MySqlSugar 3.X API

作為支持.NET CORE 為數不多的ORM之一,除了具有優越的性能外,還擁有強大的功能,不只是滿足你的增,刪,查和改。實質上擁有更多你想像不到的功能,當你需要實現某個功能時會發現有這個功能太棒了。

 

所有版本

ASP.NET 4.0+ MSSQL https://github.com/sunkaixuan/SqlSugar

ASP.NET CORE MSSQL https://github.com/sunkaixuan/ASP_NET_CORE_ORM_SqlSugar

ASP.NET 4.0+ MYSQL https://github.com/sunkaixuan/MySqlSugar

ASP.NET CORE MYSQL https://github.com/sunkaixuan/ASP_NET_CORE_ORM_MySqlSugar

ASP.NET 4.0+ Sqlite https://github.com/sunkaixuan/SqliteSugar

ASP.NET 4.0+ ORACLE https://github.com/sunkaixuan/OracleSugar

 

優點

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

SqlSugar 語法易用簡單 ,有漂亮的拉姆達語法,也支持Dapper SQL和ADO.NET(存儲過程等)的所有功能

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

SqlSugar 支持.NET CORE , 多個資料庫

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

 

連接資料庫

1.簡單用法

using(var db = new SqlSugarClient(ConnectionString)){

    //use object
    var list=db.Queryable<T>().ToList();

}

 

2.打包用法,推薦

/// <summary>
/// SqlSugar
/// </summary>
public class SugarDao
{
    private SugarDao()
    {

    }
    public static string ConnectionString
    {
        get
        {
            string reval = "server=.;uid=sa;pwd=sasa;database=SqlSugarTest"; 
            return reval;
        }
    }
    public static SqlSugarClient GetInstance()
    {
        var db = new SqlSugarClient(ConnectionString);
        db.IsEnableLogEvent = true;//Enable log events
        db.LogEventStarting = (sql, par) => { Console.WriteLine(sql + " " + par+"\r\n"); };
        return db;
    }
}

使用打包對象

using (var db = SugarDao.GetInstance())
{
    var list=db.Queryable<T>().ToList();
}

 

3.高級玩法,基於IOC和指揮官模式的DEMO

https://github.com/sunkaixuan/ASPNETMVCCRUDDEMO

 

查詢

1. Queryable 拉姆達查詢

                //查詢所有
                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 singleByPk = db.Queryable<Student>().InSingle(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 list6 = db.Queryable<Student>().In(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 =SqlSugarTool.PackagingSQL(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 = queryable.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()).ToList(); //ObjToString會將null轉轉成""
                var r2 = db.Queryable<InsertTest>().Where(it => it.d1 == par1.ObjToDate()).ToList();
                var r3 = db.Queryable<InsertTest>().Where(it => it.id == 1.ObjToInt()).ToList();//ObjToInt會將null轉轉成0
                var r4 = db.Queryable<InsertTest>().Where(it => it.id == 2.ObjToDecimal()).ToList();
                var r5 = db.Queryable<InsertTest>().Where(it => it.id == 3.ObjToMoney()).ToList();
                var r6 = db.Queryable<InsertTest>().Where(it => it.v1 == par2.Trim()).ToList();
                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();
                var c5 = db.Queryable<Student>().Where(c => c.name.Equals("小傑")).ToList();
                var c6 = db.Queryable<Student>().Where(c => c.name.Length > 4).ToList();
                var time = db.Queryable<InsertTest>().Where(c => c.d1>DateTime.Now.AddDays(1)).ToList();
                var time2 = db.Queryable<InsertTest>().Where(c => c.d1 > DateTime.Now.AddYears(1)).ToList();
                var time3 = db.Queryable<InsertTest>().Where(c => c.d1 > DateTime.Now.AddMonths(1)).ToList();

  

2. SqlQuery 原生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 id from Student limit 0,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 limit 0,1").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的值


                ////存儲過程優化操作
                //var pars2 = SqlSugarTool.GetParameters(new { p1 = 1, p2 = 0 }); //將匿名對象轉成SqlParameter
                //db.CommandType = CommandType.StoredProcedure;//指定為存儲過程可比上面少寫EXEC和參數
                //var spResult3 = db.SqlQuery<School>("sp_school", pars2);
                //db.CommandType = CommandType.Text;//還原回預設


                //獲取第一行第一列的值
                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拼接器

                //多表查詢
                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(1)");//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

 

插入

支持了高性能批量插入,讓你事辦功倍

 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;//有值


                //SqlBulkCopy同樣支持不挺入列設置
                db.SqlBulkCopy(GetInsertList());

 

 

更新

                //指定列更新
                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 array=new int[]{1,2,3};
                db.Update<School>(new { name = "藍翔2" }, it => array.Contains(it.id));// id in 1,2,3


                //支持字典更新,適合動態許可權
                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());

 

刪除

                //刪除根據主鍵
                db.Delete<School, int>(10);

                //刪除根據表達示
                db.Delete<School>(it => it.id > 100);//支持it=>array.contains(it.id)
 
                //主鍵批量刪除
                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.Delete(new School() { id = 200 });

                //根據字元串刪除
                db.Delete<School>("id=@id", new { id = 100 });

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

 

 

 更多功能

1、枚舉支持

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

 

 

2、實體生成加T4

View Code

使用T4

詳細教程:

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

 

 

3、ADO.NET

                var r1 = db.GetDataTable("select * from student");
                var r2 = db.GetSingle<Student>("select  * from student LIMIT 0,1");
                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   name from student LIMIT 0,1");
                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 MySqlParameter("@id",1) );

 

4、日誌記錄功能

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

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;
            }
        }
    }
}

 

5、別名錶功能

using System;
using System.Collections.Generic;
	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • JDBCday04_大對象_Dao_DBUtil_JavaBean 大對象 (一般不用) clob(海量文字,如圖書) blob(二進位數據,如圖片,音樂,電影) clob海量文字存入資料庫 : FileReader(讀文本) + PreparedStatement的setCharacterStre ...
  • 1、單機MySQL的美好年代 在90年代,一個網站的訪問量一般都不大,用單個資料庫完全可以輕鬆應付。在那個時候,更多的都是靜態網頁,動態交互類型的網站不多。 上述架構下,我們來看看數據存儲的瓶頸是什麼?1.數據量的總大小 一個機器放不下時2.數據的索引(B+ Tree)一個機器的記憶體放不下時3.訪問 ...
  • 官方說5.5開始就廢棄mysql_query()這塊東西很多,當然常用的就幾個還是看手冊吧。 這裡簡單記錄一下。在我失憶之後可以找回一點記憶。最近一直用框架原生的都快忘了。 1.打開mysql連接 $resource1 = mysql_connect('localhost', 'root', 'ro ...
  • 字元串截斷函數是指:Stuff 和 SubString,字元串查找函數是:CharIndex 和 PatIndex 一,SubString 截取子串 最常用的字元串函數,用於截取特定長度的子串。 參數說明: start 參數:整數,表示開始位置;字元的序號(index)從1開始,即第一個字元的序號是 ...
  • 今天遇到了一個問題,要查詢今天添加到一個表中的數據,後來解決了,嗯,記錄一下: SELECT * FROM 表1 WHERE convert(varchar(10),表1.創建時間,120)=CONVERT(VARCHAR(10),GETDATE(),120) 如果是本月的話: SELECT * F ...
  • Centos6.5之ssh免密碼登錄配置 centos ssh 免密碼登錄 0.說明 這裡為了方便說明問題,假設有A和B兩台安裝了centos6.5的主機。目標是實現A、B兩台主機分別能夠通過ssh免密碼登錄到對方主機。不同主機的配置過程一樣,這裡介紹A主機的配置過程。 事先在AB主機分別創建好要免 ...
  • 一、說明 安裝環境 centos6.6 (64位) python2.7.10 (升級系統預設python版本的方法參見 "在CentOS 6.5上安裝python2.7" ) 約定 工作目錄假定為當前用戶的HOME目錄 安裝的各軟體版本以文檔編寫時的最新版為基準,請結合實際情況參考。 尖括弧""包括 ...
  • 簡介 ABP提供了一個緩存介面,它內部使用了這個緩存介面。雖然介面的預設實現是MemoryCache,但可以用任何其它實現的緩存供應器。Abp.RedisCache包用Redis實現了緩存(查看下方的“Redis 緩存集成”)。 ICacheManager 緩存的主要介面是ICacheManager ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...