高性能ORM 框架之 MySqlSugar

时间:2021-08-20 18:58:56

mysql 3.X API地址:  http://www.cnblogs.com/sunkaixuan/p/5987308.html

MySqlSugar 1.5 API

一、介简

SqlSugar ORM框架一直在升级当中,昨天将EMIT架构进行了重构,让类型转换更加智能,EMIT转换后的性能和原生ADO同水准(以前只是接近),为了提高性能、稳定、有问必答、有需求必改、坚持更新。例如数据库类型为BIT我们在程序里面可以使用 INT接收也可以用BOOL接收,不影响一丝性能,这些都是SQLSUGAR以前没有的功能。

经过一天的努力,MySql版本所有的例子都已经测试通过:

MySql .NET 4.0+

https://github.com/sunkaixuan/MySqlSugar

MySql .NET CORE

下周更新

MSQL .NET 4.0+下载地址:

https://github.com/sunkaixuan/SqlSugar

MSSQL .NET Core版本

https://github.com/sunkaixuan/ASP_NET_CORE_ORM_SqlSugar

优点:

1、优越的性能,查询使用  reflection.emit 创建IL语言+委托绑定 然后对该对象进行 cache ,datareader直接赋值给cache对象,高性能拉姆达解析,查询速度达到原生最高性能的写法水准

2、大量语法糖,拉姆达表达示筛选,新颖的多表查询 ,方便的分页等

3、支持事务

4、内置实体类生成函数,无需使用第三方代码生成器

5、简单好用、例子齐全有问必答。

组成:

sqlSugar是由sqlSugarClient提供统一调用模式 ,sqlSugarClient是由5个部分组成

1、自身函数

2、实体生成

3、单表查询

4、多表查询

5、基类函数

MySql教程

和MSSQL版本基本一样但是个别例子也会有些细节上的区别

一、查询

1、拉姆达查询(以后会支持多表JOIN)

语法简洁和EF相似,但有区别的SqlSugar更适合字符串操作,例如Where("Id>@id",new{id=1})

   //针对单表或者视图查询
var dt= db.GetDataTable("select * from Student");
//查询所有
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 == );
//查询单条没有记录返回空对象
var single2 = db.Queryable<Student>().Where(c => c.id == ).SingleOrDefault(); //查询第一条
var first = db.Queryable<Student>().Where(c => c.id == ).First();
var first2 = db.Queryable<Student>().Where(c => c.id == ).FirstOrDefault(); //取10-20条
var page1 = db.Queryable<Student>().Where(c => c.id > ).OrderBy(it=>it.id).Skip().Take().ToList(); //上一句的简化写法,同样取10-20条
var page2 = db.Queryable<Student>().Where(c => c.id > ).OrderBy(it => it.id).ToPageList(, ); //查询条数
var count = db.Queryable<Student>().Where(c => c.id > ).Count(); //从第2条开始以后取所有
var skip = db.Queryable<Student>().Where(c => c.id > ).OrderBy(it => it.id).Skip().ToList(); //取前2条
var take = db.Queryable<Student>().Where(c => c.id > ).OrderBy(it => it.id).Take().ToList(); // Not like
string conval = "三";
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(); // 可以在拉姆达使用 ToString和 Convert,比EF出色的地方
var convert1 = db.Queryable<Student>().Where(c => c.name == "a".ToString()).ToList();
var convert2 = db.Queryable<Student>().Where(c => c.id == Convert.ToInt32("")).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(); //支持字符串Where 让你解决,更复杂的查询
var student12 = db.Queryable<Student>().Where(c => "a" == "a").Where("id>100").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 == );
bool isAny1 = db.Queryable<Student>().Any(c => c.id == ); int maxId = db.Queryable<Student>().Max<Student, int>("id");
int minId = db.Queryable<Student>().Where(c => c.id > ).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[] { "", "", "" };
var intList = intArray.ToList();
var list0 = db.Queryable<Student>().In(it => it.id, , , ).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 < ).GroupBy(it => it.sex).Select("sex,count(*) as Count").ToDynamic();
var list8 = db.Queryable<Student>().Where(c => c.id < ).GroupBy(it => it.sex).GroupBy(it => it.id).Select("id,sex, count(*) as Count").ToDynamic();
List<SexTotal> list9 = db.Queryable<Student>().Where(c => c.id < ).GroupBy(it => it.sex).Select<Student, SexTotal>("Sex, count(*) as Count").ToList();
List<SexTotal> list10 = db.Queryable<Student>().Where(c => c.id < ).GroupBy("sex").Select<Student, SexTotal>("Sex, count(*) as Count").ToList();
//SELECT Sex,Count=count(*) FROM Student WHERE 1=1 AND (id < 20) GROUP BY Sex --生成结果

2、sqlable 接近SQL的一个路线。

放弃了传统的EF写法,让他更接近SQL,可以取代传统的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 = }); //多表分页
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", , ); //多表分页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", , ); //--------转成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 = });
var list2 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToJson("*", new { id = });
var list3 = db.Sqlable().From("student", "s").Join("school", "l", "s.sch_id", "l.id and l.id=@id", JoinType.INNER).SelectToDataTable("*", new { id = }); //分页
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", , , new { id = });
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", , , new { id = });
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", , , new { id = }); //--------拼接-----//
Sqlable sable = db.Sqlable().From<Student>("s").Join<School>("l", "s.sch_id", "l.id", JoinType.INNER);
string name = "a";
int id = ;
if (!string.IsNullOrEmpty(name))
{
sable = sable.Where("s.name=@name");
}
if (!string.IsNullOrEmpty(name))
{
sable = sable.Where("s.id=@id or s.id=100");
} var pars = new { id = id, name = name };
int pageCount = sable.Count(pars);
var list7 = sable.SelectToPageList<Student>("s.*","l.id desc",,, pars); }

3、对原生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 = });
//转成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").First();
//反回键值
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 name from Student").First();
//存储过程
//var spResult = db.SqlQuery<School>("exec sp_school @p1,@p2", new { p1=1,p2=2 });
}

4、容器的转换

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

二、更新

可以指定列更新,也可对实体整个更新,也可以排除不更新字段非常的方便好用

 int id = ;
using (var db = SugarDao.GetInstance())
{
//指定列更新
db.Update<School>(new { name = "蓝翔2" }, it => it.id == id);
db.Update<School, int>(new { name = "蓝翔2" }, , , );
db.Update<School, string>(new { name = "蓝翔2" }, new string[] { "", "" }); //整个实体更新
db.Update(new School { id = id, name = "蓝翔2" });
db.Update<School>(new School { id = id, name = "蓝翔2" }, it => it.id == id); //设置不更新列
db.DisableUpdateColumns = new string[] { "CreateTime" };//设置CreateTime不更新 TestUpdateColumns updObj = new TestUpdateColumns()
{
VGUID = Guid.Parse("6DF396EB-D1C8-48A5-8BE1-D58D685646A7"),
Name = "xx",
Name2 = "xx2",
IdentityField = ,
CreateTime = null
}; //CreateTime将不会被更新
db.Update(updObj);
//以前实现这种更新需要用指定列的方式实现,现在就简单多了。 }

更新

三、删除

 using (var db = SugarDao.GetInstance())
{
//真删除
db.Delete<Student, int>();//注意主键必需为实体类的第一个属性
db.Delete<School>(it => it.id > );
db.Delete<School, string>(new string[] { "", "", "" }); //假删除
//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);
}

删除

四、插入

Student s = new Student()
{
name = "张" + new Random().Next(, int.MaxValue)
}; db.Insert(s); //插入一条记录 (有主键也好,没主键也好,有自增列也好都可以插进去) List<Student> list = new List<Student>()
{
new Student()
{
name="张"+new Random().Next(,int.MaxValue)
},
new Student()
{
name="张"+new Random().Next(,int.MaxValue)
}
}; db.InsertRange(list); //批量插入

插入

五、枚举支持

 using (SqlSugarClient db = SugarDao.GetInstance())
{
var stuList= db.Queryable<Student>().ToList();
db.Insert<Student>(new Student() { sch_id = SchoolEnum.蓝翔2 });
db.Update<Student>(new Student() { sch_id=SchoolEnum.蓝翔2 , id=} );
var stuList2 = db.Queryable<Student>().Where(it=>it.sch_id==SchoolEnum.蓝翔1).ToList();
}

枚举

六、实体生成

 using (var db = SugarDao.GetInstance())
{ //根据当前数据库生成所有表的实体类文件 (参数:SqlSugarClient ,文件目录,命名空间)
db.ClassGenerating.CreateClassFiles(db,"e:\\mysqlModel","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 * from Student", "student");
}

实体生成

除了上面代码还有T4生成看DEMO不懂可以随时问我

七、全局过滤器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySqlSugar;
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=}};
}
},
{ "org",()=>{
return new KeyValueObj(){ Key=" orgId=@orgId" , Value=new{ orgId=}};
}
},
};
public static SqlSugarClient GetInstance()
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings[@"sqlConn"].ToString(); //这里可以动态根据cookies或session实现多库切换
var reval = new SqlSugarClient(connection);
reval.SetFilterFilterParas(_filterParas);
return reval;
}
}
}

过滤器

八、别名表

 using (SqlSugarClient db = SugarDao.GetInstance())
{ //-----单个-------//
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);
}

别名表

九、事务

using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接
{
db.IsNoLock = true;//启用无锁查询
db.CommandTimeOut = ;//设置超时时间
try
{
db.BeginTran();//开启事务
//db.BeginTran(IsolationLevel.ReadCommitted);+3重载可以设置事世隔离级别 db.CommitTran();//提交事务
}
catch (Exception)
{
db.RollbackTran();//回滚事务
throw;
}
}

十、保留了ADO功能

 using (SqlSugarClient db = SugarDao.GetInstance())//开启数据库连接
{
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");
}

MySql版已经发布到Nuget,方便大家下载