开源ORM框架 SqlSugar 3.0的巨大变化

Posted 孙凯旋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了开源ORM框架 SqlSugar 3.0的巨大变化相关的知识,希望对你有一定的参考价值。

 

3.1.x ,将作为3.X系统的最后一个版本,下面将会开发 全新的功能

更新列表:https://github.com/sunkaixuan/SqlSugar/releases

 

优点:

 

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设计   实体类没有任何属性完全原生态

 

 

所有版本:

 

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 CORE Sqlite https://github.com/sunkaixuan/ASP_NET_CORE_ORM_MySqlSugar

 

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

  

连接数据库

 

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

 

0、功能预览

                /****************************基本功能**************************************/
                //查询
                case "select": demo = new Select(); break;
                //删除
                case "delete": demo = new Delete(); break;
                //插入
                case "insert": demo = new Insert(); break;
                //更新
                case "update": demo = new Update(); break;
                //基层函数的用法
                case "ado": demo = new Ado(); break;
                //事务
                case "tran": demo = new Tran(); break;
                //创建实体函数
                case "createclass": demo = new CreateClass(); break;
                //T4生成 http://www.cnblogs.com/sunkaixuan/p/5751503.html

                //日志记录
                case "log": demo = new Log(); break;
                //枚举支持
                case "enum": demo = new EnumDemo(); break;


                
                /****************************实体映射**************************************/
                //自动排除非数据库列
                case "ignoreerrorcolumns": demo = new IgnoreErrorColumns(); break;
                //别名表
                case "mappingtable":demo=new MappingTable(); break;
                //别名列
                case "mappingcolumns": demo = new MappingColumns(); break;
                //通过属性的方法设置别名表和别名字段
                case "attributesmapping": demo = new AttributesMapping(); break;



                /****************************业务应用**************************************/
                //过滤器
                case "filter": demo = new Filter(); break;
                //过滤器2
                case "filter2": demo = new Filter2(); break;
                //流水号功能
                case "serialnumber": demo = new SerialNumber(); break;

                //多语言支持 http://www.cnblogs.com/sunkaixuan/p/5709583.html
                //多库并行计算 http://www.cnblogs.com/sunkaixuan/p/5046517.html



                /****************************支持**************************************/
                //公开函数数
                case "pubmethod": demo = new PubMethod(); break;
                //Sql2012分页的支持
                case "sqlpagemodel": demo=new SqlPageModel(); break;
                //设置ToJson的日期格式
                case "serializerdateformat":demo =new SerializerDateFormat();break;

                default: Console.WriteLine("switchOn的值错误,请输入正确的 case"); break;

 

 

1、使用拉姆达进行查询

                //查询所有
                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、使用原生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.idORM框架,sqlsugar学习一

sqlsugar freesql hisql 三个ORM框架性能测试对比

c# sqlsugar,hisql,freesql orm框架全方位性能测试对比之sqlserver

Zara原创SqlSugar4轻量级ORM框架的使用指南

c# sqlsugar,hisql,freesql orm框架全方位性能测试对比 sqlserver 性能测试

SqlSugar入门到熟练使用 : SqlSugar ORM介绍和ORM对象创建