ORM之SqlSugar

前言:本文将从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<Student>();
            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<Student>().ToList();

            //2:根据主键查询单条数据
            var model = _client.Queryable<Student>().InSingle(1);

            //3:根据条件查询
            var list2 = _client.Queryable<Student>().Where(it => it.Sex == "").ToList();

            //4:分页查询
            var total = 0;
            var getPage = _client.Queryable<Student>().Where(it => it.Age > 18).ToPageList(1, 2, ref total);//分页查询

            //5:两张表联合查询(其中Student为学生表、Class为班级表;JoinType为连接方式(Inner,Left,Right)、第二个为两张表的关联字段)
            //5.1 方式一
            var query = _client.Queryable<Student, Class>((a, b) => new object[] {
                JoinType.Left,
                a.ClassId==b.Id
            });

            //5.2:方式二 (未指定连接方式默认Inner)
            query = _client.Queryable(_client.Queryable<Student>(), _client.Queryable<Class>(), (a, b) => a.ClassId == b.Id);

            //5.3:方式三 (指定连接方式)
            query = _client.Queryable(_client.Queryable<Student>(), _client.Queryable<Class>(), 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<Student>();

            //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<Student>();

            //1:根据实体删除
            var count = _client.Deleteable(data).ExecuteCommand();

            //2:根据主键删除
            count = _client.Deleteable<Student>(1).ExecuteCommand();

            //3:根据条件删除
            count = _client.Deleteable<Student>()
                   .Where(t => t.Age < 19)
                   .ExecuteCommand();

            //4:批量实体删除
            count = _client.Deleteable(list).ExecuteCommand();

            //5:批量根据主键删除
            List<int> ids = new List<int>();
            count = _client.Deleteable<Student>(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<SugarParameter> pms = new List<SugarParameter>();
            pms.Add(new SugarParameter("id", 1));

            //1:写SQL,分页、查询条件用表达式
            _client.SqlQueryable<Student>("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>(TResult thisValue);//针对这个列进行取平均数统计
    public static int AggregateCount<TResult>(TResult thisValue);// 统计这个列数量 等价于 SQL里的 count(x)
    public static int AggregateDistinctCount<TResult>(TResult thisValue);/ 返回去重之后的数量
    public static TResult AggregateMax<TResult>(TResult thisValue);//返回最大值
    public static TResult AggregateMin<TResult>(TResult thisValue);// 返回最小值
    public static TResult AggregateSum<TResult>(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>(T[] thisValue, object InField);// 数组是否包含
    public static bool ContainsArray<T>(List<T> thisValue, object InField);//列表苏菲包含
    public static bool ContainsArrayUseSqlParameters<T>(List<T> thisValue, object InField);//
    public static bool ContainsArrayUseSqlParameters<T>(T[] thisValue, object InField);//
    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, object parameterValue);//是否相等
    public static DateTime GetDate();//返回当前数据库时间
    public static string GetRandom();//
    public static TResult GetSelfAndAutoFill<TResult>(TResult value);//
    public static bool HasNumber(object thisValue);//返回是否大于0,且不能为Null
    public static bool HasValue(object thisValue);// 是否有值,且不为Null
    public static CaseThen IF(bool condition);// sql 里的if判断
    public static TResult IIF<TResult>(bool Expression, TResult thenValue, TResult elseValue);// case when
    public static TResult IsNull<TResult>(TResult thisValue, TResult ifNullValue);// sql 里的 IsNull
    public static bool IsNullOrEmpty(object thisValue);//判断是否是Null或者空
    public static int Length(object value);//取长度
    public static TResult MappingColumn<TResult>(TResult oldColumnName, string newColumnName);// 列名映射
    public static string MergeString(string value1, string value2);
    public static string MergeString(string value1, string value2, string value3, string value4);
    public static string MergeString(string value1, string value2, string value3, string value4, string value5);
    public static string MergeString(string value1, string value2, string value3, string value4, string value5, string value6);
    public static string MergeString(string value1, string value2, string value3);
    public static string MergeString(string value1, string value2, string value3, string value4, string value5, string value6, string value7);
    public static string Replace(object value, string oldChar, string newChar);// 替换
    public static bool StartsWith(string thisValue, string parameterValue);
    public static Subqueryable<T> Subqueryable<T>() where T : class, new();
    public static string Substring(object value, int index, int length);// 获取子串
    public static bool ToBool(object value);//类型转换
    public static DateTime ToDate(object value);// 类型转换
    public static decimal ToDecimal(object value);// 类型转换
    public static double ToDouble(object value);// 类型转换
    public static Guid ToGuid(object value);// 类型转换
    public static int ToInt32(object value);// 类型转换
    public static long ToInt64(object value);// 类型转换
    public static string ToLower(object thisValue);// 类型转换
    public static string ToString(object value);// 类型转换
    public static TimeSpan ToTime(object value);// 类型转换
    public static string ToUpper(object thisValue);// 类型转换
    public static string Trim(object thisValue);// 去除首尾的空格
}

参考网址:查询 - 查询函数 - 《SqlSugar 4.0 文档》 - 书栈网 · BookStack

SqlSugar官网:https://www.donet5.com/Doc/99999999999/1197

以上就是SqlSugar的一些简单使用,其他复杂用法可以上官网学习,最后不得的不感慨一句,SqlSugar太强大了~

不积跬步,无以至千里;不积小流,无以成江海。ヾ(◍°∇°◍)ノ゙
原文地址:https://www.cnblogs.com/jiangxianshen/p/15346868.html