老程序员分享:ORM之SqlSugar

简介: 老程序员分享: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();


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,

相关文章
|
SQL XML 前端开发
比mybatis还好的ORM,有点GraphQL语法的味道
个新的类似ORM的框架,具备了ORM框架的功能,同时也还有一点 GraphQL语法的味道,这个新的框架叫Bean Searcher
320 0
|
20天前
|
开发框架 前端开发 JavaScript
基于SqlSugar的开发框架循序渐进介绍(1)--框架基础类的设计和使用
基于SqlSugar的开发框架循序渐进介绍(1)--框架基础类的设计和使用
|
SQL XML 缓存
认识 ORM 框架 Hibernate,为什么 2022 年了还在谈论它?
前言 Hibernate 作为一种全自动 ORM 框架,在几年前常与 Spring、Struts2 一起使用,并称 SSH,作为主流的企业级应用框架。伴随着 MyBatis 的诞生,以及 Hibernate 本身的一些缺陷,如今 Hibernate 已经慢慢淡出了大家的视野。
690 0
认识 ORM 框架 Hibernate,为什么 2022 年了还在谈论它?
|
Java 数据库连接 数据库
返璞归真,学了那么多技术栈,那些 [Mybatis-plus] 之 CRUD操作你还熟悉吗
返璞归真,学了那么多技术栈,那些 [Mybatis-plus] 之 CRUD操作你还熟悉吗
68 0
|
SQL 关系型数据库 MySQL
Django框架之ORM
Django框架之ORM
93 0
Django框架之ORM
|
JSON JavaScript 前端开发
程序员接活利器,dataTable组件带你快速开发,摆脱CRUD
程序员接活利器,dataTable组件带你快速开发,摆脱CRUD
257 0
程序员接活利器,dataTable组件带你快速开发,摆脱CRUD
|
SQL 安全 Go
GoFrame ORM 使用实践分享
今天这篇把我使用GoFrame ORM的过程中认为有价值、可能踩坑、比较好的实践等相关的知识点分享出来。
361 0
|
XML Java 数据库连接
学习MyBatis必知必会(1)~准备工作:了解框架、三层架构、ORM思想
学习MyBatis必知必会(1)~准备工作:了解框架、三层架构、ORM思想
128 0
学习MyBatis必知必会(1)~准备工作:了解框架、三层架构、ORM思想
|
SQL 存储 NoSQL
为什么说ORM是一种反模式
上周我在twitter上讨论了ORM,在那以后有人希望我澄清一下。事实上,我曾经写文章讨论过ORM, 但那是时的上下文是关于SQL的,我不应该把这将两件事情混为一谈。
205 0
为什么说ORM是一种反模式
|
前端开发 JavaScript .NET
【ABP框架系列学习】介绍篇(1)
原文:【ABP框架系列学习】介绍篇(1)   0.引言 该系列博文主要在【官方文档】及【tkbSimplest】ABP框架理论研究系列博文的基础上进行总结的,或许大家会质问,别人都已经翻译过了,这不是多此一举吗?原因如下: 1.【tkbSimplest】的相关博文由于撰写得比较早的,在参照官方文档学习的过程中,发现部分知识未能及时同步(当前V4.0.2版本),如【EntityHistory】、【Multi-Lingual Engities】章节未涉及、【Caching】章节没有Entity Caching等内容。
1894 0