高性能框架 SqlSugar.ORM 2.3

2018-09-05 23:47

阅读:1094

  前言

  SqlSugar从去年到现在已经一年了,版本从1.0升到了现在的2.3 ,这是一个稳定版本 ,有数家公司已经项目上线,在这里我将SqlSugar的功能重新整理成一篇新的贴子,希望大家喜欢。

  公司团队项目、产品已经完全抛弃EF,SqlSugar定位不是ORM,而是为了方面的让你去写Sql。

  支持Json 、Dynamic、 List、 List、 ValueType和 Dictionary 等多种类型的返回值也是一大亮点。

  执行十万次【将拉姆达】转成【Sql】只用了1秒多(机型:Surface Pro4 I5 8G)

  更多测试(机型:过时机器)

   二、功能介绍

  查询

  1、SqlQuery 用于执行原生SQL和存储过程

   //转成list List list1 = db.SqlQuery("select * from Student"); //转成list带参 List list2 = db.SqlQuery("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("select top 1 id from Student").Single(); //反回键值 Dictionary list6 = db.SqlQuery>("select id,name from Student").ToDictionary(it => it.Key, it => it.Value); //反回List var list7 = db.SqlQuery("select top 1 id,name from Student").Single(); //存储过程 var spResult = db.SqlQuery("exec sp_school @p1,@p2", new { p1=1,p2=2 }); Sql查询

  2、Queryable 用于单表或者视图查询

   //---------Queryable,扩展函数查询---------// //针对单表或者视图查询 //查询所有 var student = db.Queryable().ToList(); var studentDynamic = db.Queryable().ToDynamic(); var studentJson = db.Queryable().ToJson(); //查询单条 var single = db.Queryable().Single(c => c.id == 1); //查询单条没有记录返回空对象 var single2 = db.Queryable().Where(c => c.id == 1).SingleOrDefault(); //查询第一条 var first = db.Queryable().Where(c => c.id == 1).First(); var first2 = db.Queryable().Where(c => c.id == 1).FirstOrDefault(); //取10-20条 var page1 = db.Queryable().Where(c => c.id > 10).OrderBy("id").Skip(10).Take(20).ToList(); //上一句的简化写法,同样取10-20条 var page2 = db.Queryable().Where(c => c.id > 10).OrderBy("id").Skip(2).ToList(); //取前2条 var take = db.Queryable().Where(c => c.id > 10).OrderBy("id").Take(2).ToList(); // Not like string conval = "a"; var notLike = db.Queryable().Where(c => c.name == "a".ToString()).ToList(); var convert2 = db.Queryable().Where(c => c.id == Convert.ToInt32("1")).ToList();// var convert3 = db.Queryable().Where(c => DateTime.Now > Convert.ToDateTime("2015-1-1")).ToList(); var convert4 = db.Queryable().Where(c => DateTime.Now > DateTime.Now).ToList(); //支持字符串Where 让你解决,更复杂的查询 var student12 = db.Queryable().Where(c => "a" == "a").Where("id>100").ToList(); var student13 = db.Queryable().Where(c => "a" == "a").Where("id>100 and id in( select 1)").ToList(); //存在记录反回true,则否返回false bool isAny100 = db.Queryable().Any(c => c.id == 100); bool isAny1 = db.Queryable().Any(c => c.id == 1); int maxId = db.Queryable().Max("id"); int minId = db.Queryable().Where(c => c.id > 0).Min("id"); //In var list1= db.Queryable().In("id", new string[] { "1", "2", "3" }).ToList(); var list3=db.Queryable().In("id", new List { "1", "2", "3" }).ToList(); var list4 = db.Queryable().Where(it=>it.id<10).In("id", new List { "1", "2", "3" }).ToList(); //分组查询 var list5= db.Queryable().Where(c => c.id < 20).GroupBy("sex").Select("Sex,Count=count(*)").ToList(); //SELECT Sex,Count=count(*) FROM Student WHERE 1=1 AND (id < 20) GROUP BY Sex --生成结果 单表查询

  3、Sqlable 用于多表查询

   //---------Sqlable,创建多表查询---------// //多表查询 List dataList = db.Sqlable() .Form("school", "s") .Join("student", "st", "st.id", "s.id", JoinType.INNER) .Join("student", "st2", "st2.id", "st.id", JoinType.LEFT) .Where("s.id>100 and s.id<@id") .Where("1=1")//可以多个WHERE .SelectToList("st.*", new { id = 1 }); //多表分页 List dataPageList = db.Sqlable() .Form("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("st.*", "s.id", 1, 10); //多表分页WHERE加子查询 List dataPageList2 = db.Sqlable() .Form("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("st.*", "s.id", 1, 10); //--------转成List Dynamic 或者 Json-----// //不分页 var list1 = db.Sqlable().Form("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToDynamic("*", new { id = 1 }); var list2 = db.Sqlable().Form("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToJson("*", new { id = 1 }); var list3 = db.Sqlable().Form("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToDataTable("*", new { id = 1 }); //分页 var list4 = db.Sqlable().Form("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().Form("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().Form("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().Form("s").Join("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("s.*","l.id desc",1,20, pars); 多表查询

  4、新容器转换

   using (SqlSugarClient db = SugarDao.GetInstance()) { var list2= db.Queryable().Where(c => c.id < 10).Select(c => new classNew { newid = c.id, newname = c.name, xx_name = c.name }).ToList();//不支持匿名类转换,也不建议使用 var list3 = db.Queryable().Where(c => c.id < 10).Select(c => new { newid = c.id, newname = c.name, xx_name = c.name }).ToDynamic();//匿名类转换 } 新容器转换

  添加

   using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接 { Student s = new Student() { name = "张ert(s); //插入一条记录 (有主键也好,没主键也好,有自增列也好都可以插进去) List list = new List() { new Student() { name="张"+new Random().Next(1,int.MaxValue) }, new Student() { name="张"+new Random().Next(1,int.MaxValue) } }; db.InsertRange(list); //批量插入 } } 添加

  更新

   using (var db = SugarDao.GetInstance()) { //指定列更新 db.Update(new { name = "蓝翔2" }, it => it.id == id); db.Update(new { name = "蓝翔2" }, 1, 3, 12); db.Update(new { name = "蓝翔2" }, new string[] { "1", "2" }); //整个实体更新 db.Update(new School { id = id, name = "蓝翔2" }); db.Update(new School { id = id, name = "蓝翔2" }, it => it.id == id); //设置不更新列 db.DisableUpdateColumns = new string[] { "CreateTime" };//设置CreateTime不更新 TestUpdateColumns updObj = new TestUpdateColumns() { VGUID = Guid.Parse("542b5a27-6984-47c7-a8ee-359e483c8470"), Name = "xx", Name2 = "xx2", IdentityField = 0, CreateTime = null }; //CreateTime将不会被更新 db.Update(updObj); //以前实现这种更新需要用指定列的方式实现,现在就简单多了。 } 更新

  删除和假删除

   using (var db = SugarDao.GetInstance()) { //真删除 db.Delete(10);//注意主键必需为实体类的第一个属性 db.Delete(it => it.id > 100); db.Delete(new string[] { "100", "101", "102" }); //假删除 //db.FalseDelete("is_del", 100); //等同于 update school set is_del=0 where id in(100) //db.FalseDelete("is_del", it=>it.id==100); } 删除

  全局过滤器

  这功能主要用于通用权限设计等功能, 当有很多WHERE重复,并且动态 这时候就需要在全局设置好过滤器接口集合,程序中使用只需要设KEY便可

   /// /// 过滤器 /// 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().ToList(); //通过全局过滤器对需要权限验证的数据进行过滤 //相当于db.Queryable().Where("id=@id",new{id=1}) //sqlable var list2 = db.Sqlable().Form("s").SelectToList("*"); //同上 //sqlQuery var list3 = db.SqlQuery("select * from Student"); //同上 } } } /// /// 扩展SqlSugarClient /// public class SugarDaoFilter { //禁止实例化 private SugarDaoFilter() { } /// /// 页面所需要的过滤函数 /// private static Dictionary> _filterParas = new Dictionary 过滤器

  无参模式

  将IsGetPageParas设为true之后页面的参数都不需要使用 new{}来赋值

   using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接 { db.IsGetPageParas = true;//使用无参模式直接将Requst中的ID传给@id无需在代码中写出来 var list = db.Queryable().Where("id=@id").ToList(); //sqlable queryable sqlquery通用 //获取页面所有参数到键值对 //var kvs= SqlSugarTool.GetParameterDictionary(); //以前写法 //var xx = db.Queryable().Where("id=@id", new { id=Request["id"] }).ToList(); } 无参

  事务

   using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接 { db.IsNoLock = true;//启用无锁查询andTimeOut = 30000;//设置超时时间 try { db.BeginTran();//开启事务 db.CommitTran();//提交事务 } catch (Exception) { db.RollbackTran();//回滚事务 throw; } } 事务

  公开函数

   //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();//对字符串防注入处理sage); } //SqlLikeWordEncode 处理LIKE特殊字符 var likestr = SqlSugarTool.SqlLikeWordEncode("[%%%"); //GetParameterArray 获取页面参数所有参数的键和值 var pars = SqlSugarTool.GetParameterArray(); //将匿名对象转成SqlParameter var par3= SqlSugarTool.GetParameters(new { id=1}); 函数

  实体生成

   //根据当前数据库生成所有表的实体类文件 (参数: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"); //根据SQL语句生成class字符串 var str2 = db.ClassGenerating.SqlToClass(db, "select top 1 * from Student", "student"); 实体生成

  T4模版

  请查看Demos文件下的T4

  别名表

   //-----单个-------// var list = db.Queryable("Student").ToList();//查询的是 select * from student 而我的实体名称为V_Student //-----全局多个设置-------// //设置 Mapping Table 如果没这方面需求可以传NULL List mappingTableList = new List(){ new KeyValue(){ Key="FormAttr", Value="Flow_FormAttr"}, new KeyValue(){ Key="Student3", Value="Student"} }; db.SetMappingTables(mappingTableList); 别名表

  多库并行计算功能

   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(s, false/*false表示不是自增列*/); //数据库设计主键为GUID为佳多库计算不会冲突 ////并发请求所有节点找出这条数据更新= "改11"; //db.Update(s, it => it.id == s.id);//根据表达示更新 //db.Update(s, s.id);//根据主键更新 //db.Update(s, new Guid[] { s.id });//根据主键数组更新 ////并发请求所有节点找出这条数据删除 //db.Delete("SELECT max(NUM) FROM STUDENT").Tasks; foreach (var dr in taskDataTable)//遍历所有节点数据 { var dt = dr.Result.DataTable;//每个节点的数据 类型为nectionString; } //多线程请求所有数据库节点,获取汇总结果 var taskInt = db.Taskable("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("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("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 groupList3 = db.Taskable("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("SELECT max(NUM) FROM STUDENT").Max();//求出所有节点的最大值 int minValue = db.Taskable("SELECT min(NUM) FROM STUDENT").Min();//求出所有节点的最小值 var dataCount = db.Taskable("SELECT count(1) FROM STUDENT").Count();//求出所有节点数据 // var avg = db.TaskableWithCount("SELECT avg(num)", " FROM STUDENT").Avg(); var all = db.Taskable("select * from student where Contains(name,@name)"/*使用contains需要建全文索引*/, new { name = "张三" }).ToList();//获取所有节点name为张三的数据,转为list var dnSingle = DateTime.Now; var data = db.Taskable("select * from student where id=@id", new { id = id }).ToSingle();//从所有节点中查询一条记录 var timeSingle = (DateTime.Now - dnSingle).TotalSeconds; var dn = DateTime.Now; //单列排序 // var list = db.TaskableWithPage("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("id", "select * from student "/*使用contains需要建全文索引*/, 5000, 25, ref pageCount, new List() { 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; } 多库模式 /// /// 测试类 /// public class student { public Guid id { get; set; } public string name { get; set; } public DateTime createTime { get; set; } public int num { get; set; } } /// /// 获取数据库连接对象 /// public class CloudDao { private CloudDao() { } public static CloudClient GetInstance() { return new CloudClient(new List() { 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}, }); } } 多库配置


评论


亲,登录后才可以留言!