前言:本文将从SqlSugar的介绍、SqlSugar的优点、SqlSugar的具体使用对该ORM框架做简单的学习记录
SqlSugar的介绍
SqlSugar ORM,NET 4.+ & .NET CORE 高性能轻量级ORM框架,众多.NET框架中最容易使用的数据库访问技术。
SqlSugar的优点
高性能 。不夸张的说,去掉Sql在数据库执行的时间,SqlSugar是EF数倍性能,另外在批量操作和一对多查询上也有不错的SQL优化
高扩展性 。支持自定义拉姆达函数解析、扩展数据类型、支持自定义实体特性,外部缓存等
稳定性和技术支持。 虽然不是官方ORM, 但在稳定性上也是有着数年用户积累,如果遇到问题可以在GITHUB提出来,会根据紧急度定期解决
功能全面。虽然SqlSugar小巧可功能并不逊色于EF框架
创新、持续更新 ,向下兼容
SqlSugar的使用
项目依赖项中添加SQLSugarCore(如果用的是.NET Freamwork 选择 Sqlsugar即可),这里项目用的是.NET Core 3.1 所以选择安装 SqlSugarCore
我在项目中新增了一个SqlSugarHelper的帮助类,先来看看数据库连接配置:
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
namespace Common.Helper.ORM
{
public class SqlSugarHelper
{
SqlSugarClient _client = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "",//数据库连接字符串
DbType = DbType.SqlServer,//设置数据库类型
IsAutoCloseConnection = true,//自动释放数据库,如果存在事务,在事务结束后释放
InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
});
}
}
连接配置中有个DbType,具体枚举类如下:
namespace SqlSugar
{
public enum DbType
{
MySql = 0,
SqlServer = 1,
Sqlite = 2,
Oracle = 3,
PostgreSQL = 4,
Dm = 5,
Kdbndp = 6
}
}
可以看出,目前SqlSugar 支持的数据库有:MySql、SqlServer、Sqlite、Oracle、PostgreSQL、Dm、Ddbndp,基本包含了主流常用的数据库类型
然后从CRUD对SqlSugar的用法做个介绍:
C-Create 创建/新增:
示例如下:
//1:新增返回影响行数
var data = new Student() { Name = "zhangsan", ClassId = 101, Sex = "男", Age = 22 };
int count = _client.Insertable(data).ExecuteCommand();
//2:返回自增列
int newId = _client.Insertable(data).ExecuteReturnIdentity();
//3:插入返回新增的实体
var newModel = _client.Insertable(data).ExecuteReturnEntity();
//4:只插入部分列
count = _client.Insertable(data)
.InsertColumns(t => new { t.Name, t.ClassId })
.ExecuteReturnIdentity();
//5:忽略部分列
count = _client.Insertable(data)
.IgnoreColumns(t => new { t.Age })
.ExecuteReturnIdentity();
//6:根据条件指定不插入列
count = _client.Insertable(data)
.IgnoreColumns(t => t.Age < 18)
.ExecuteReturnIdentity();
//7:插入使用锁
count = _client.Insertable(data)
.With(SqlWith.UpdLock)
.ExecuteReturnIdentity();
//8:批量插入(性能很快不用操心)
var list = new List();
list.Add(new Student() { Name = "zhangsan", ClassId = 101, Sex = "男", Age = 22 });
list.Add(new Student() { Name = "lisi", ClassId = 101, Sex = "男", Age = 23 });
_client.Insertable(list).ExecuteCommand();
_client.Insertable(list.ToArray()).ExecuteCommand();
R-Retrieve 检索/查询:
部分示例如下:
//1:查询所有数据
var list = _client.Queryable().ToList();
//2:根据主键查询单条数据
var model = _client.Queryable().InSingle(1);
//3:根据条件查询
var list2 = _client.Queryable().Where(it => it.Sex == "男").ToList();
//4:分页查询
var total = 0;
var getPage = _client.Queryable().Where(it => it.Age > 18).ToPageList(1, 2, ref total);//分页查询
//5:两张表联合查询(其中Student为学生表、Class为班级表;JoinType为连接方式(Inner,Left,Right)、第二个为两张表的关联字段)
//5.1 方式一
var query = _client.Queryable((a, b) => new object【】 {
JoinType.Left,
a.ClassId==b.Id
});
//5.2:方式二 (未指定连接方式默认Inner)
query = _client.Queryable(_client.Queryable(), _client.Queryable(), (a, b) => a.ClassId == b.Id);
//5.3:方式三 (指定连接方式)
query = _client.Queryable(_client.Queryable(), _client.Queryable(), JoinType.Left, (a, b) => a.ClassId == b.Id);
U-Update:更新:
示例如下:
var data = new Student() { Id = 1, Name = "zhangsan", ClassId = 101, Sex = "男", Age = 22 };
var list = new List();
//1:根据实体更新(主键要有值,主键是更新条件)
var count = _client.Updateable(data).ExecuteCommand();
//2:传入对象根据条件更新
count = _client.Updateable(data)
.WhereColumns(t => new { t.Id })
.ExecuteCommand();
//3:更新部分列
count = _client.Updateable(data)
.UpdateColumns(x => new { x.Name, x.Age, x.ClassId })
.WhereColumns(t => new { t.Id })
.ExecuteCommand();
//4:批量更新
count = _client.Updateable(list).ExecuteCommand();
D-Delete:删除:
示例如下:
var data = new Student() { Id = 1, Name = "zhangsan", ClassId = 101, Sex = "男", Age = 22 };
var list = new List();
//1:根据实体删除
var count = _client.Deleteable(data).ExecuteCommand();
//2:根据主键删除
count = _client.Deleteable(1).ExecuteCommand();
//3:根据条件删除
count = _client.Deleteable()
.Where(t => t.Age < 19)
.ExecuteCommand();
//4:批量实体删除
count = _client.Deleteable(list).ExecuteCommand();
//5:批量根据主键删除
List[span style="color: rgba(0, 0, 255, 1)">intint
count = _client.Deleteable(ids).ExecuteCommand();
再来看看SqlSugar的其他用法:
实体类用法:
//如果实体类名称和表名不一致可以加上SugarTable特性指定表名
【SugarTable("Student")】
public class StudentModel
{
//指定主键和自增列,当然数据库中也要设置主键和自增列才会有效
【SugarColumn(IsPrimaryKey = true, IsIdentity = true)】
public int Id { get; set; }
public string Name { get; set; }
}
根据实体类创建对象:
_client.CodeFirst.SetStringDefaultLength(200/设置varchar默认长度为200/).InitTables(typeof(StudentModel));//执行完数据库就有这个表了
原生SQL执行:
string sql = "select from student";
List pms = new List();
pms.Add(new SugarParameter("id", 1));
//1:写SQL,分页、查询条件用表达式
_client.SqlQueryable("select from student").Where(it => it.Id ==1).ToPageList(1, 2);
//2:纯SQL
_client.Ado.ExecuteCommand(sql, pms);
//3:执行存储过程
_client.Ado.UseStoredProcedure();
var count = _client.Ado.UseStoredProcedure().ExecuteCommand("存储过程名称", pms);
var dt = _client.Ado.UseStoredProcedure().GetDataTable("存储过程名称", pms);
SqlSugar 常用函数:
public class SqlFunc
{
public static TResult AggregateAvg(TResult thisValue);//针对这个列进行取平均数统计
public static int AggregateCount(TResult thisValue);// 统计这个列数量 等价于 SQL里的 count(x)
public static int AggregateDistinctCount(TResult thisValue);/ 返回去重之后的数量
public static TResult AggregateMax(TResult thisValue);//返回最大值
public static TResult AggregateMin(TResult thisValue);// 返回最小值
public static TResult AggregateSum(TResult thisValue);// 返回总和
public static bool Between(object value, object start, object end);// 判断列的值是否在两个值之间
public static int CharIndex(string findChar, string searchValue);// SQL 的charindex
public static bool Contains(string thisValue, string parameterValue);// 是否包含
public static bool ContainsArray(T【】 thisValue, object InField);// 数组是否包含
public static bool ContainsArray(List thisValue, object InField);//列表苏菲包含
public static bool ContainsArrayUseSqlParameters(List thisValue, object InField);//
public static bool ContainsArrayUseSqlParameters(T【】 thisValue, object InField);//
//代码效果参考:http://www.jhylw.com.cn/594241825.html
public static DateTime DateAdd(DateTime date, int addValue, DateType dataType);// 时间添加public static DateTime DateAdd(DateTime date, int addValue);// 日期添加
public static bool DateIsSame(DateTime date1, DateTime date2);// 时间是否相同
public static bool DateIsSame(DateTime? date1, DateTime? date2);//时间是否相同
public static bool DateIsSame(DateTime date1, DateTime date2, DateType dataType);//时间是否相同,根据DateType判断
public static int DateValue(DateTime date, DateType dataType);// 根据dateType, 返回具体的时间值
public static bool EndsWith(string thisValue, string parameterValue);//字符串是否以某些值结尾
public static bool Equals(object thisValue,