国产精品ORM框架-SqlSugar详解
1、SqlSugar初识
2、开始实操
3、增删改操作
4、进阶功能
5、集成整合
6、脚手架应用
sqlsugar 官网-CSDN博客
国产精品ORM框架-SqlSugar详解 SqlSugar初识 专题二-CSDN博客
1、SqlSugar初识
1.1 基本概念和历史
SqlSugar 是一款 老牌 .NET 开源ORM框架,由果糖大数据科技团队维护和更新 ,开箱即用
最易上手的ORM框架 。
ORM框架:以面向对象的思想去操作数据库的框架。
1.2 SqlSugar支持功能
支持 .NET 百万级【大数据】写入和更新、分表和几十亿查询和统计等 拥有成熟方案
支持 完整的SAAS一套应用 跨库查询 、租户分库 、租户分表 和 租户数据隔离
支持【低代码】+工作流 (无实体多库兼容CRUD & JSON TO SQL )
语法最爽的ORM、优美的表达式、仓储、UnitOfWork、DbContext、AOP `
支持 DbFirst、CodeFirst和【WebFirst】 3种模式开发
简单易用、功能齐全、高性能、轻量级、服务齐全、官网教程文档、有专业技术支持一天18小时
服务
2、开始实操
2.0 如何学习?
1、执行数据库脚本,初始化数据库
2、使用vs链接数据库中,得到链接字符串
3、配置链接字符串到CustomConnectionConfig配置类中
2.1 环境要求
VS2022开发工具
DOTNET6平台 控制台程序
SQL Server
SqlSugar version:5.1.3.32
2.2、DbFirst快速上手
DbFrist:映射迁移方式,从数据库中把表生成实体对象,数据库先行。先把数据库设计好。直接生成
实体;
Nuget: SqlSugarCore
快速链接数据库操作数据库;
准备数据库--SqlSugarDb
准备数据库链接字符串
Data Source=3 1,14331\\MSSQLSERVER2014;Initial Catalog=ZhaoxiSqlSugarDb;User ID=sa;Password= ;Encrypt=False
nuget引入程序集SqlSugarCor
配置SqlClient
生成实体
ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = "Data Source=PC-202406030027;Initial Catalog=ZhaoxiSqlSugarDb;User ID=sa;Password=sa123",IsAutoCloseConnection = true,DbType = DbType.SqlServer};//SqlSugarClient:链接数据库的对象 using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//参数1:路径 参数2:命名空间
//IsCreateAttribute 代表生成SqlSugar特性
{db.DbFirst.IsCreateAttribute().CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models", "Models");
}//格式化文件名
{db.DbFirst.FormatFileName(x => x.ToLower()).CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models");
}
//强制可以空类型string加上?
{db.DbFirst.StringNullable().CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models");
}
//生成实体并且带有筛选
{db.DbFirst.Where("Student").CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models", "Models");db.DbFirst.Where(it => it.ToLower().StartsWith("snow")).CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models", "Models");db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models", "Models");
}
//生成带有SqlSugar特性的实体
{db.DbFirst.IsCreateAttribute().CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models", "Models");
}
//生成实体带有默认值
{db.DbFirst.IsCreateDefaultValue().CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models", "Demo.Models");
}//自定义格式化功能
{db.DbFirst //类 .SettingClassTemplate(old => { return old;/*修改old值替换*/ }) //类构造函数.SettingConstructorTemplate(old => { return old;/*修改old值替换*/ }).SettingNamespaceTemplate(old =>{return old + "\r\nusing SqlSugar;"; //追加引用SqlSugar}).SettingPropertyDescriptionTemplate(old => { return old;/*修改old值替换*/}) //属性备注.SettingPropertyTemplate((columns, temp, type) => //属性:新重载 完全自定义用配置{var columnattribute = "\r\n [SugarColumn({0})]";List<string> attributes = new List<string>();if (columns.IsPrimarykey)attributes.Add("IsPrimaryKey=true");if (columns.IsIdentity)attributes.Add("IsIdentity=true");if (attributes.Count == 0){columnattribute = "";}return temp.Replace("{PropertyType}", type).Replace("{PropertyName}", columns.DbColumnName).Replace("{SugarColumn}", string.Format(columnattribute, string.Join(",", attributes)));}).CreateClassFile("E:\\zhaoxi\\gongkaike\\Zhaoxi.DotNet.Demo\\Zhaoxi.SqlSugar.Models");
}
//格式化文件名
//生成带有SqlSugar特性的实体
自定义格式化功能
2.3、CodeFirst快速上手
代码先行,先有代码,然后有数据库,只关注业务,业务中的对象如果需要就直接创建实体,对应的数
据库表,由代码一次生成;
准备实体对象
准备数据库链接字符串
nuget引入程序集SqlSugarCore
配置SqlClient
生成数据库和表
数据库的结构完全由代码来决定,数据库表--主键、自增,字段类型。。。。。
特性列表 ---用在类的属性---对应的是数据库中的表的某一个字段
名称 描述
IsIdentity 是否创建自增标识
IsPrimaryKey 是否创建主键标识
ColumnName 创建数据库字段的名称(默认取实体类属性名称)
ColumnDataType
创建数据库字段的类型用法1: “varchar(20)” 不需要设置长度用
法2: 不设置该参数 系统会根据C#类型自动生成相应的数据库类型 用
法3: 多库兼容可以用 :看标题9
IsIgnore ORM不处理该列
ColumnDescription 备注 表注释 (新版本支持XML文件)
Length 长度 设成10会生成 xxx类型(10), 没括号的不设置
IsNullable 是否可以为null默为false
DecimalDigits 精度 如 decimal(18,2) length=18,DecimalDigits=2
OracleSequenceName 设置Oracle序列,设置后该列等同于自增列
OldColumnName 修改列名用,这样不会新增或者删除列
IndexGroupNameList 创建索引用
UniqueGroupNameList 创建唯一索引
注意:有2个属性用处不
同DefaultValue
IsOnlyIgnoreInsert
DefaultValue=默认值 用来建表设置字段默认值
IsOnlyIgnoreInsert=true 插入数据时取默认值很多情况需要2个一
起使用如果只建表不插入数据用1个 如果建表并且插入数据用2个
IsIdentity 是否创建自增标识
IsPrimaryKey 是否创建主键标识
ColumnName 创建数据库字段的名称(默认取实体类属性名称)
ColumnDataType
创建数据库字段的类型用法1: “varchar(20)” 不需要设置长度用
法2: 不设置该参数 系统会根据C#类型自动生成相应的数据库类型 用
法3: 多库兼容可以用 :看标题9
IsIgnore ORM不处理该列
ColumnDescription 备注 表注释 (新版本支持XML文件)
Length 长度 设成10会生成 xxx类型(10), 没括号的不设置
IsNullable 是否可以为null默为false
DecimalDigits 精度 如 decimal(18,2) length=18,DecimalDigits=2
OracleSequenceName 设置Oracle序列,设置后该列等同于自增列
OldColumnName 修改列名用,这样不会新增或者删除列
IndexGroupNameList 创建索引用
UniqueGroupNameList 创建唯一索引
注意:有2个属性用处不
同DefaultValue
IsOnlyIgnoreInsert
DefaultValue=默认值 用来建表设置字段默认值
IsOnlyIgnoreInsert=true 插入数据时取默认值很多情况需要2个一
起使用如果只建表不插入数据用1个 如果建表并且插入数据用2个
/// <summary>/// CodeFirst/// </summary>public static void CodeFirstShow(){ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//如果不存在创建数据库存在不会重复创建 {db.DbMaintenance.CreateDatabase(); // 注意 :Oracle和个别国产库需不支持该方法,需要手动建库 }//创建表根据实体类CodeFirstTable1 {db.CodeFirst.InitTables(typeof(CodeFirstTable1));//这样一个表就能成功创建了}//创建单个表 {db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(CodeFirstTable1));//这样一个表就能成功创建了}//手动建多个表 {db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(CodeFirstTable1), typeof(CodeFirstTable2));}//批量创建表//语法1:{Type[] types = Assembly.LoadFrom("Zhaoxi.SqlSugar.Models.dll")//如果 .dll报错,可以换成 xxx.exe 有些生成的是exe .GetTypes().Where(it => it.FullName.Contains("CodeFirst"))//命名空间过滤,当然你也可以写其他条件过滤.ToArray();//断点调试一下是不是需要的Type,不是需要的在进行过滤 //判断如果数据库存在这个表,就删除表foreach (Type type in types){if (db.DbMaintenance.IsAnyTable(type.Name, false)){db.DbMaintenance.DropTable(type.Name);}} //然后创建db.CodeFirst.SetStringDefaultLength(200).InitTables(types);//根据types创建表}//语法2: {Type[] types = typeof(CodeFirstTable1).Assembly.GetTypes().Where(it => it.FullName.Contains("CodeFirst"))//命名空间过滤,当然你也可以写其他条件过滤.ToArray();//判断如果数据库存在这个表,就删除表foreach (Type type in types){if (db.DbMaintenance.IsAnyTable(type.Name, false)){db.DbMaintenance.DropTable(type.Name);}}db.CodeFirst.SetStringDefaultLength(200).InitTables(types);//根据types创建表}//动态设置表名{db.CodeFirst.As<UnituLong>("UnituLong0011").InitTables<UnituLong>();}}}
特殊支持
如果大量使用 ColumnDataType="nvarchar(50)" 自定义类型将无法很好的支持多种数据库,比如很
多库不支持nvarchar
当然你也可以使用AOP替换 ColumnDataType 去实现多库,下面介绍自带的方案
/// <summary>/// CodeFirst/// </summary>public static void CodeFirstShow(){ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = "Data Source=PC-202406030027;Initial Catalog=ZhaoxiSqlSugarDb_Info;Integrated Security=True",IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//如果不存在创建数据库存在不会重复创建 {db.DbMaintenance.CreateDatabase(); // 注意 :Oracle和个别国产库需不支持该方法,需要手动建库 }//创建表根据实体类CodeFirstTable1 {db.CodeFirst.InitTables(typeof(CodeFirstTable1));//这样一个表就能成功创建了}//创建单个表 {db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(CodeFirstTable1));//这样一个表就能成功创建了}//手动建多个表 {db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(CodeFirstTable1), typeof(CodeFirstTable2));}//批量创建表//语法1:{Type[] types = Assembly.LoadFrom("Zhaoxi.SqlSugar.Models.dll")//如果 .dll报错,可以换成 xxx.exe 有些生成的是exe .GetTypes().Where(it => it.FullName.Contains("CodeFirst"))//命名空间过滤,当然你也可以写其他条件过滤.ToArray();//断点调试一下是不是需要的Type,不是需要的在进行过滤 //判断如果数据库存在这个表,就删除表foreach (Type type in types){if (db.DbMaintenance.IsAnyTable(type.Name, false)){db.DbMaintenance.DropTable(type.Name);}} //然后创建db.CodeFirst.SetStringDefaultLength(200).InitTables(types);//根据types创建表}//语法2: {Type[] types = typeof(CodeFirstTable1).Assembly.GetTypes().Where(it => it.FullName.Contains("CodeFirst"))//命名空间过滤,当然你也可以写其他条件过滤.ToArray();//判断如果数据库存在这个表,就删除表foreach (Type type in types){if (db.DbMaintenance.IsAnyTable(type.Name, false)){db.DbMaintenance.DropTable(type.Name);}}db.CodeFirst.SetStringDefaultLength(200).InitTables(types);//根据types创建表}//动态设置表名{db.CodeFirst.As<UnituLong>("UnituLong0011").InitTables<UnituLong>();}}}
//创建表根据实体类CodeFirstTable1
//创建单个表
{
db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(CodeFirstTable1));//这样一个表就能成功创建了
}
//批量创建表
//命名空间过滤,当然你也可以写其他条件过滤
//动态设置表名
{
db.CodeFirst.As<UnituLong>("UnituLong0011").InitTables<UnituLong>();
}
2.4、索引支持
普通索引
唯一索引 (true表示唯一索引)
复合普通索引
给索引添加占位符 占位符 {table} {db}
/// <summary>/// CodeFirst创建索引/// </summary>public static void CodeFirstIndexShow(){ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = "Data Source=PC-202406030027;Initial Catalog=ZhaoxiSqlSugarDb_NewInfo;Integrated Security=True",IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//创建表根据实体类CodeFirstTable3 {db.CodeFirst.InitTables(typeof(CodeFirstTable3));//这样一个表就能成功创建了}}}
[SugarIndex("index_codetable3_name", nameof(CodeFirstTable3.Name), OrderByType.Asc)] //普通索引--非聚集索引[SugarIndex("unique_codetable3_CreateTime", nameof(CodeFirstTable3.CreateTime), OrderByType.Desc, true)] //唯一索引 (true表示唯一索引) [SugarIndex("index_codetable3_nameid", nameof(CodeFirstTable3.Name), OrderByType.Asc, nameof(CodeFirstTable1.Id), OrderByType.Desc)] //复合普通索引[SugarIndex("{db}index_codetable3_name", nameof(CodeFirstTable3.Description), OrderByType.Asc)] //使用 {db} 进行占位符替换,小写不要有空格[SugarIndex("index_{table}_name", nameof(CodeFirstTable3.DescriptionNew), OrderByType.Asc)] //表名占位符(自动分表不需要加这个自动的)[SugarIndex("IndexUnituadfasf3_longx{include:name,id}", nameof(IndexUnituadfasf), OrderByType.Asc)][SugarTable("CodeFirstTable3", TableDescription = "表备注")]//表添加备注public class CodeFirstTable3{[SugarColumn(IsIdentity = true, IsPrimaryKey = true)]public int Id { get; set; }public string? Name { get; set; }[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custompublic string? Text { get; set; }[SugarColumn(IsNullable = true)]public DateTime CreateTime { get; set; }[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custompublic string? Description { get; set; }[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custompublic string? DescriptionNew { get; set; }[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custompublic string? IndexUnituadfasf { get; set; }}
2.5、库表操作
名称 备注 返回
类型
GetDataBaseList 获取所有数据库名称 List
GetViewInfoList 查询所有视图 List
GetTableInfoList 获取所有表,查询所有的表
(GetTableInfoList(是否缓存)) List
GetColumnInfosByTableName 获取列根据表名,获取字段,字段信息
GetColumnInfosByTableName(表名,是否缓存) List
GetIsIdentities 获取自增列 List
GetPrimaries 获取主键 List
IsAnyTable 表是否存在,判断表存不存在 ( IsAny(表名,是否
缓存)) bool
IsAnyColumn 列是否存在 bool
IsPrimaryKey 主键是否存在 bool
IsIdentity 自增是否存在 bool
IsAnyConstraint 约束是否存在 bool
2.4、索引支持
普通索引
唯一索引 (true表示唯一索引)
复合普通索引
给索引添加占位符 占位符 {table} {db}
2.5、库表操作
名称 备注 返回
类型
DropTable 删除表 bool
TruncateTable 清空表 bool
CreateTable
创建表说明:如果有实体类优先用CodeFirst建
表,这个是底层方法用该方法建表,因为数据库不
同,有些属性需要用单纯写个方法去创建,当前表
格这些方法都有现成的
bool
AddColumn 添加列 bool
UpdateColumn 更新列 bool
AddPrimaryKey 添加主键 bool
DropConstraint 删除约束 bool
BackupDataBase 备份库 bool
DropColumn 删除列 bool
RenameColumn 重命名列 bool
AddDefaultValue 添加默认值 bool
AddTableRemark 添加表描述,表注释 bool
AddColumnRemark 添加列描述,表注释 bool
DeleteColumnRemark 删除列描述,表注释 bool
RenameTable 重命名表 bool
CreateIndex 创建索引 bool
IsAnyIndex 索引是否存在 bool
类型
GetDataBaseList 获取所有数据库名称 List
GetViewInfoList 查询所有视图 List
GetTableInfoList 获取所有表,查询所有的表
(GetTableInfoList(是否缓存)) List
GetColumnInfosByTableName 获取列根据表名,获取字段,字段信息
GetColumnInfosByTableName(表名,是否缓存) List
GetIsIdentities 获取自增列 List
GetPrimaries 获取主键 List
IsAnyTable 表是否存在,判断表存不存在 ( IsAny(表名,是否
缓存)) bool
IsAnyColumn 列是否存在 bool
IsPrimaryKey 主键是否存在 bool
IsIdentity 自增是否存在 bool
IsAnyConstraint 约束是否存在 bool
2.4、索引支持
普通索引
唯一索引 (true表示唯一索引)
复合普通索引
给索引添加占位符 占位符 {table} {db}
2.5、库表操作
名称 备注 返回
类型
DropTable 删除表 bool
TruncateTable 清空表 bool
CreateTable
创建表说明:如果有实体类优先用CodeFirst建
表,这个是底层方法用该方法建表,因为数据库不
同,有些属性需要用单纯写个方法去创建,当前表
格这些方法都有现成的
bool
AddColumn 添加列 bool
UpdateColumn 更新列 bool
AddPrimaryKey 添加主键 bool
DropConstraint 删除约束 bool
BackupDataBase 备份库 bool
DropColumn 删除列 bool
RenameColumn 重命名列 bool
AddDefaultValue 添加默认值 bool
AddTableRemark 添加表描述,表注释 bool
AddColumnRemark 添加列描述,表注释 bool
DeleteColumnRemark 删除列描述,表注释 bool
RenameTable 重命名表 bool
CreateIndex 创建索引 bool
IsAnyIndex 索引是否存在 bool
using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
{Console.WriteLine("GetDataBaseList============================");foreach (var item in db.DbMaintenance.GetDataBaseList(db)){Console.WriteLine(item);}Console.WriteLine("GetViewInfoList============================");foreach (var item in db.DbMaintenance.GetViewInfoList(false)){Console.WriteLine(item);}Console.WriteLine("GetTableInfoList============================");foreach (var item in db.DbMaintenance.GetTableInfoList(false)){Console.WriteLine(item.Name);}Console.WriteLine("GetIsIdentities============================");foreach (var item in db.DbMaintenance.GetIsIdentities("CodeFirstTable3")){Console.WriteLine(item);}Console.WriteLine("GetPrimaries============================");foreach (var item in db.DbMaintenance.GetPrimaries("CodeFirstTable3")){Console.WriteLine(item);}if (db.DbMaintenance.IsAnyTable("CodeFirstTable3", false)){db.DbMaintenance.DropTable("CodeFirstTable3");}//db.DbMaintenance.DropTable("CodeFirstTable3");//.....
}
3、增删改操作
3.1、数据插入数据库
插入 单条
字典插入
忽略插入
批量 插入
雪花ID插入
Guid主键自动赋值 函数
注意 说明
插入返回值:
using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){db.CodeFirst.InitTables(typeof(Snowflake));db.CodeFirst.InitTables(typeof(Student));#region 单条插入{int count = db.Deleteable<Student>().ExecuteCommand();//插入返回自增列 (实体除ORACLE外实体要配置自增,Oracle需要配置序列)int idPk = db.Insertable(student).ExecuteReturnIdentity();//返回雪花ID 看文档3.0具体用法(在最底部)Snowflake snowflakeModel = new Snowflake(){Name = "返回雪花ID",SchoolId = 1};db.Deleteable<Snowflake>().ExecuteCommand();long id = db.Insertable(snowflakeModel).ExecuteReturnSnowflakeId();//实用技巧2: 强制设置表名(默认表名来自实体) db.Insertable(student).AS("dbstudent").ExecuteCommand();//字典插入Dictionary<string, object> dc = new Dictionary<string, object>();dc.Add("StudentName", "字典插入"); //不能写实体中的属性名,必须和数据库保持一致dc.Add("SchoolId", 23);dc.Add("CreateTime", DateTime.Now);db.Insertable(dc).AS("dbstudent").ExecuteCommand();db.Deleteable<Student>().ExecuteCommand();//匿名对象 插入var obj = new{StudentName = "匿名对象 插入",CreateTime = DateTime.Now,SchoolId = "456"};db.Insertable<Dictionary<string, object>>(obj).AS("[dbstudent]").ExecuteCommand();}#endregion#region 忽略-不插入指定字段{db.Deleteable<Student>().ExecuteCommand();//忽略 name SchoolIdint id = db.Insertable(student).IgnoreColumns(it => new { it.Name }).ExecuteReturnIdentity();db.Insertable(student).IgnoreColumns("Name", "SchoolId").ExecuteReturnIdentity();}#endregion#region 只插入指定字段{db.Deleteable<Student>().ExecuteCommand();//忽略 name testidint id = db.Insertable(student).InsertColumns(it => new { it.Name }).ExecuteReturnIdentity();db.Insertable(student).InsertColumns("Name", "SchoolId").ExecuteReturnIdentity();}#endregion#region 批量插入{db.Deleteable<Student>().ExecuteCommand();List<Student> addlist = new List<Student>();for (int i = 0; i < 100; i++){addlist.Add(new Student(){Name = $"Name_{i}",SchoolId = i,CreateTime = DateTime.Now});}//(1)、非参数化插入(防注入) //优点:综合性能比较平均,列少1万条也不慢,属于万写法,不加事务情况下部分库有失败回滚机质//缺点:数据量超过5万以上占用内存会比较大些,内存小可以用下面2种方式处理db.Insertable(addlist).ExecuteCommand();//(2)、使用参数化内部分页插入//优点:500条以下速度最快,兼容所有类型和emoji,10万以上的大数据也能跑,就是慢些,内部分批量处理过了。//缺点:500以上就开始慢了,要加事务才能回滚 db.Insertable(addlist).UseParameter().ExecuteCommand();//5.0.3.8-Preview及以上版本支持(NUGET搜索勾上包括预览)//(3)、大数据写入(特色功能:大数据处理上比所有框架都要快30%)//优点:1000条以上性能无敌手//缺点:不支持数据库默认值, API功能简单, 小数据量并发执行不如普通插入,插入数据越大越适合用这个//新功能 5.0.44db.Fastest<Student>().PageSize(100000).BulkCopy(addlist);}#endregion#region 分页插入{db.Deleteable<Student>().ExecuteCommand(); List<Student> addlist = new List<Student>();for (int i = 0; i < 100; i++){addlist.Add(new Student(){Name = $"Name_{i}",SchoolId = i,CreateTime = DateTime.Now});}//分页插入 ,如果不支持db.Fastest分页插入也是可以提升一下性能的db.Utilities.PageEach(addlist, 10, pageList =>{db.Insertable(pageList).ExecuteCommand();//db.Insertable(List<实体>).UseParameter().ExecuteCommand() 可以试试和上面哪个性能高用哪个});}#endregion#region 大数据插入{List<Student> students = new List<Student>();db.Deleteable<Student>().ExecuteCommand();for (int i = 0; i < 1000000; i++){students.Add(new Student(){Name = $"Name_{i}",SchoolId = i,CreateTime = DateTime.Now});}//Stopwatch stopwatch = Stopwatch.StartNew();//stopwatch.Start();插入 100万 数秒时间//db.Insertable<Student>(students).ExecuteCommand();//性能 比现有任何Bulkcopy都要快30%//stopwatch.Stop();//Console.WriteLine($"普通方式:1000000条数据大概用时:{stopwatch.ElapsedMilliseconds} 毫秒");db.Deleteable<Student>().ExecuteCommand();Stopwatch stopwatch1 = Stopwatch.StartNew();stopwatch1.Start();//插入 100万 数秒时间db.Fastest<Student>().BulkCopy(students);//性能 比现有任何Bulkcopy都要快30%stopwatch1.Stop();Console.WriteLine($"BulkCopy大数据操作:1000000条数据大概用时:{stopwatch1.ElapsedMilliseconds} 毫秒");}#endregion#region Guid主键自动赋值 {//只要设置为主键,并且C#类型是Guid 只要不传值,会自动赋值 // 注意只能用: ExecuteCommand 方法不能用自增列的方法db.CodeFirst.InitTables(typeof(UserInfo));db.Deleteable<UserInfo>().ExecuteCommand();UserInfo user = new UserInfo(){Name = "Richard老师",CreateTime = DateTime.Now,};db.Insertable(user).ExecuteCommand();}#endregion#region 调用实体内方法{db.CodeFirst.InitTables(typeof(UnitInsertMethod));db.Deleteable<UnitInsertMethod>().ExecuteCommand();db.Insertable(new UnitInsertMethod() { Name = "1" }).CallEntityMethod(it => it.Create()).ExecuteCommand();db.Updateable(new UnitInsertMethod() { Name = "1" }).CallEntityMethod(it => it.modify("admint")).ExecuteCommand();}#endregion#region Select Into 临时表{db.Ado.OpenAlways();//长连接db.Queryable<UserInfo>().Select(" * into #temp").ToList();//插入临时表var tempList = db.Queryable<dynamic>().AS("#temp").ToList();//查询临时表}#endregion}
}
3.2、数据修改
输出Sql语句
单条更新
按需更新
批量修改
大数据量操作
只更新某列-选择更新
NULL列不更新
更新忽略null字段
无主键/指定列更新
条件更新
重新赋值更新
表达式更新
插入返回值:
ExecuteCommand
返回受影响行数 , update where 如果没找到那么就会返回
0
ExecuteCommandHasChange
返回bool ,等同于 bool isChange= ExecuteCommand()>0
/// <summary>/// 修改数据/// </summary>public static void UpdateData(){//如何输出Sql语句 ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = CustomConnectionConfig.ConnectionString001,IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//初始化一条数据测试使用db.Insertable<Student>(new Student(){CreateTime = DateTime.Now,Name = "测试数据",SchoolId = 1,}).ExecuteCommand();{ //输出Sql语句db.Aop.OnLogExecuting = (s, p) =>{Console.WriteLine("----------------------------");Console.WriteLine($"Sql语句:{s}");};}Student student = db.Queryable<Student>().First();//单条更新{student.CreateTime = DateTime.Now;db.Updateable<Student>(student).ExecuteCommand(); //右标题1 下面的所有菜单}//按需更新{db.Tracking(student);//创建跟踪student.Name = "a1" + Guid.NewGuid();//只改修改了name那么只会更新name//跟踪批量操作不会生效,原因:默认最佳性能(跟踪批量性能差,自已循环)//可以清空跟踪db.TempItems = null;db.Updateable(student).ExecuteCommand();}//批量修改{//List<Student> list = db.Queryable<Student>().Take(20).ToList();//foreach (var item in list)//{// item.Name = "New Name" + DateTime.Now;//}//db.Updateable(list).ExecuteCommand();批量更新中,按需是不能操作的//foreach (var item in list)//{// item.Name = "New Name 02" + DateTime.Now;//}//db.Tracking(list);//创建跟踪//db.Updateable(list).ExecuteCommand();}//大数据量操作{//db.Deleteable<Student>().ExecuteCommand();//删除所有数据//List<Student> addlist = new List<Student>();//for (int i = 0; i < 1000000; i++)//{// addlist.Add(new Student()// {// CreateTime = DateTime.Now,// Name = "Richard" + i,// SchoolId = i// });//}//初始化1000000条数据到数据库//db.Fastest<Student>().BulkCopy(addlist);大数据批量更新 适合列多数据多的更新 (MySql连接字符串要加AllowLoadLocalInfile=true )普通方式操作//{// foreach (var item in addlist)// {// item.Name = $"批量修改第一次-Updateable方式";// }// Console.WriteLine("普通方式批量修改1000000条数据开始计时~~");// Stopwatch stopwatch = new Stopwatch();// stopwatch.Start();// db.Updateable<Student>(addlist).ExecuteCommand();// stopwatch.Stop();// Console.WriteLine($"批量修改1000000条数据共:{stopwatch.ElapsedMilliseconds} ms");//}大数据量BulkUpdate操作--高性能//{// foreach (var item in addlist)// {// item.Name = $"批量修改第二次=BulkUpdate方式";// }// Console.WriteLine("大数据量操作-BulkUpdate方式批量修改1000000条数据开始计时~~");// Stopwatch stopwatch = new Stopwatch();// stopwatch.Start();// db.Fastest<Student>().BulkUpdate(addlist);// stopwatch.Stop();// Console.WriteLine($"批量修改1000000条数据共:{stopwatch.ElapsedMilliseconds} ms");//}}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//忽略某一列不更新 {Student studentUp = db.Queryable<Student>().First();studentUp.SchoolId = 234;studentUp.Name = "忽略某一列不更新";studentUp.CreateTime = DateTime.Now.AddYears(5);var result = db.Updateable(studentUp).IgnoreColumns(it => new{it.CreateTime}).ExecuteCommand();}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//只更新某列--按需更新{Student studentUp = db.Queryable<Student>().First();studentUp.SchoolId = 345;studentUp.Name = "只更新某列";studentUp.CreateTime = DateTime.Now.AddYears(6);var result = db.Updateable(studentUp).UpdateColumns(it => new { it.Name, it.CreateTime }).ExecuteCommand();}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//NULL列不更新 {Student studentUp = db.Queryable<Student>().First();studentUp.SchoolId = 456;studentUp.Name = null;//更新忽略null字段var result = db.Updateable(studentUp).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();//更新忽略null并且忽略默认值 (比如int默认值是0就不更新)var result1 = db.Updateable(studentUp).IgnoreColumns(ignoreAllNullColumns: true, ignoreAllDefaultValue: true).ExecuteCommand();}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//无主键/指定列{//WhereColumns(it=>new { it.Id,it.Name}) //条件列不会被更新,只会作为条件 Student studentUp = db.Queryable<Student>().First();studentUp.SchoolId = 567;studentUp.Name = null;var result = db.Updateable(studentUp).WhereColumns(it => new{it.Id}).ExecuteCommand();//更新单 条根据IDvar result1 = db.Updateable(studentUp).WhereColumns(it => new{it.Id}).ExecuteCommand();//更新集合根据ID by id}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//条件更新{//如果是集合操作请更新到5.0.4版本之前版本禁止使用, 并且只有部分库支持Student studentUp = db.Queryable<Student>().First();studentUp.Name = "条件更新";var result = db.Updateable(studentUp).Where(it => it.Id == 7003783).ExecuteCommand();}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//重新赋值更新{Student studentUp = db.Queryable<Student>().First();studentUp.SchoolId = 678;studentUp.Name = "重新赋值";// studentUp.Name值的基础上在处理var result = db.Updateable(studentUp).ReSetValue(it =>{it.Name = it.Name + "a";}).ExecuteCommand();//多个字段 var result1 = db.Updateable(studentUp).ReSetValue(it =>{it.Name = it.Name + "a";it.CreateTime = DateTime.Now;}).ExecuteCommand();}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//表达式更新{var result = db.Updateable<Student>().SetColumns(it => new Student(){Name = "a",CreateTime = DateTime.Now}).Where(c => c.Id == 7003783).ExecuteCommand();//正确没参数我们称为表达式更新 }}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//批量更新 In{var ids = db.Queryable<Student>().Select(c => c.Id).Take(5).ToList();var result = db.Updateable<Student>().SetColumns(it => it.Name == "a").Where(it => ids.Contains(it.Id)).ExecuteCommand();// in (1,2,3)}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//表达式无实体更新{var result = db.Updateable<DbTableInfo>().AS("dbstudent").SetColumns("StudentName", "表达式无实体更新").Where("id=7003782").ExecuteCommand();}}using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//根据字典更新{//字典Dictionary<string, object> dt = new Dictionary<string, object>();dt.Add("id", 7003782);dt.Add("StudentName", "字典更新");dt.Add("createTime", DateTime.Now);var tResult = db.Updateable(dt).AS("dbstudent").WhereColumns("id").ExecuteCommand();//字典集合var dtList = new List<Dictionary<string, object>>();dtList.Add(dt);var t666 = db.Updateable(dtList).AS("dbstudent").WhereColumns("id").ExecuteCommand();}}}
3.3、数据删除函数
说明
Deleteable方法使用
ExecuteCommand
返回受影响行数 , update where 如果没找到那么就会返回
0
ExecuteCommandHasChange
返回bool ,等同于 bool isChange= ExecuteCommand()>0
/// <summary>/// 删除数据/// </summary>public static void DeleteData(){ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = CustomConnectionConfig.ConnectionString001,IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){db.CodeFirst.InitTables(typeof(StudentInfo));//表中数据全部清空,清除,自增初始化db.DbMaintenance.TruncateTable<StudentInfo>();//输出Sql语句db.Aop.OnLogExecuting = (s, p) =>{Console.WriteLine("----------------------------");Console.WriteLine($"Sql语句:{s}");};List<StudentInfo> addlist = new List<StudentInfo>();for (int i = 0; i < 500; i++){addlist.Add(new StudentInfo(){Id = i + 1,CreateTime = DateTime.Now,Isdeleted = false,Name = $"名称_{i + 1}",SchoolId = i + 1,});}db.Deleteable<StudentInfo>().ExecuteCommand();db.Insertable<StudentInfo>(addlist).ExecuteCommand();//单个实体删除{db.Deleteable<StudentInfo>().Where(new StudentInfo() { Id = 1 }).ExecuteCommand();}//List<实体> 删除集合List<StudentInfo> list = new List<StudentInfo>(){new StudentInfo() { Id = 2 },new StudentInfo() { Id = 3 }};db.Deleteable<StudentInfo>(list).ExecuteCommandHasChange(); //批量删除//根据主键删除db.Deleteable<StudentInfo>().In(4).ExecuteCommand();//无主键删除db.Deleteable<StudentInfo>().In(it => it.Id, 5).ExecuteCommand();//根据主键数组删除db.Deleteable<StudentInfo>().In(new int[] { 6, 7 }).ExecuteCommand();//无主键数组删除db.Deleteable<StudentInfo>().In(it => it.Id, new int[] { 8, 9 }).ExecuteCommand();//表达式删除db.Deleteable<StudentInfo>().Where(it => it.Id == 10).ExecuteCommand();//无实体删除db.Deleteable<object>().AS("[StudentInfo]").Where("id=@id", new { id = 11 }).ExecuteCommand();db.Deleteable<object>().AS("[StudentInfo]").Where("id in (@id) ", new { id = new int[] { 12, 13, 14 } }).ExecuteCommand();//批量//根据字典集合删除 Dictionary<string, object> parameter = new Dictionary<string, object>();parameter.Add("Id", 15);List<Dictionary<string, object>> dic = new List<Dictionary<string, object>>(){parameter};db.Deleteable<object>().AS("[StudentInfo]").WhereColumns(dic).ExecuteCommand();}}
3.4、过滤器
通用操作的统一定制;
如果在数据库中表设计支持假删除,通过一个状态来记录当前这条数据是否被删除了;
定义了过滤器之后,定义过滤器就是一个条件,就可以把过滤器设置为全局;任何一个查询操作都会走
这个过滤器;
//配置表过滤器db.QueryFilter.Add(new TableFilterItem<StudentInfo>(it => it.Name.Contains("名称")));//查询有效 List<StudentInfo> resultlist = db.Queryable<StudentInfo>().ToList();//删除也有效db.Deleteable<StudentInfo>().EnableQueryFilter().Where(it => it.Id == 15).ExecuteCommand();//逻辑删除 请升级到5.0.4.9+//实体属性有isdelete或者isdeleted//假删除 软删除db.Deleteable<StudentInfo>().In(20).IsLogic().ExecuteCommand();//指定属性db.Deleteable<StudentInfo>().In(21).IsLogic().ExecuteCommand("Isdeleted");//指定属性并且修改时间db.Deleteable<StudentInfo>().In(22).IsLogic().ExecuteCommand("Isdeleted", 1, "CreateTime");
3.5、添加或者修改
场景:如果当前操作的数据在数据库中不存在就认为是添加操作,如果存在就修改操作;
根据主键ID来,如果ID为零,就新增--数据库中自动生成ID
如果ID不为零,就认为是修改的动作;
/// <summary>
/// 插入或更新
/// </summary>
public static void AddOrUpdate()
{ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = CustomConnectionConfig.ConnectionString001,IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){db.Deleteable<StudentInfo>().ExecuteCommand();//不存在就插入,存在就修改{StudentInfo studentInfo = new StudentInfo(){Id = 31,Name = "新增的数据",CreateTime = DateTime.Now,Isdeleted = false,SchoolId = 0,};//新功能 5.0.6.2+ //存在更新 不存在插入 (默认是主键)db.Storageable(studentInfo).ExecuteCommand();//新版才支持 studentInfo.Name = "数据已存在就修改";db.Storageable(studentInfo).ExecuteCommand();//新版才支持//批量操作---存在更新 不存在插入 List<StudentInfo> addlist = new List<StudentInfo>();for (int i = 0; i < 20; i++){addlist.Add(new StudentInfo(){Id = i + 1,CreateTime = DateTime.Now,Isdeleted = false,Name = $"名称_{i + 1}",SchoolId = i + 1,});}db.Storageable<StudentInfo>(addlist).ExecuteCommand();foreach (var item in addlist){item.Name = $"批量修改";}db.Storageable<StudentInfo>(addlist).ExecuteCommand();}StudentInfo obj = new StudentInfo(){CreateTime = DateTime.Now,Isdeleted = false,Name = $"名称_41",SchoolId = 41,};//等于0插入否则更新(不验证数据库是否存在){db.Storageable(obj).SplitUpdate(it => it.Item.Id > 0).SplitInsert(it => true).ExecuteCommand();obj.Id = 1;obj.Name = "修改一下数据";db.Storageable(obj).SplitUpdate(it => it.Item.Id > 0).SplitInsert(it => true).ExecuteCommand();}StudentInfo upobj = new StudentInfo(){Id = 51,CreateTime = DateTime.Now,Isdeleted = false,Name = $"名称_41",SchoolId = 41,};upobj.Name = "测试数据";//忽略部分字段更新{StorageableResult<StudentInfo> storageableResult = db.Storageable(upobj).ToStorage();//不存在插入storageableResult.AsInsertable.ExecuteCommand();//修改部分数据upobj.Name = "Name修改了";upobj.CreateTime = DateTime.Now.AddYears(10);//存在更新StorageableResult<StudentInfo> storageableResult1 = db.Storageable(upobj).ToStorage();storageableResult1.AsUpdateable.IgnoreColumns(z => z.Name).ExecuteCommand();var insertlist = storageableResult1.InsertList;var updateList = storageableResult1.UpdateList;}//无主键操作{upobj.CreateTime = DateTime.Now.AddYears(-5);upobj.Name = "无主键操作";db.Storageable(upobj).WhereColumns(it => it.Id)//指定一个条件,当然支持多个 new {it.id,it.name}.ExecuteCommand();//将数据进行分组 }//对于性能要求高,数据量大的可以这么操作,适合1万以上数据处理{db.Deleteable<StudentInfo>().ExecuteCommand(); //删除所有数据var addlist = new List<StudentInfo>();for (int i = 0; i < 100000; i++){addlist.Add(new StudentInfo(){Id = i + 1,CreateTime = DateTime.Now,Isdeleted = false,Name = $"名称_{i + 1}",SchoolId = i + 1,});}StorageableResult<StudentInfo> storageableResult = db.Storageable<StudentInfo>(addlist).ToStorage();storageableResult.BulkCopy();}//字典用法{db.Deleteable<StudentInfo>().ExecuteCommand();List<Dictionary<string, object>> dictionaryList = new List<Dictionary<string, object>>();Dictionary<string, object> dic = new Dictionary<string, object>();dic.Add("Id", 456789);dic.Add("SchoolId", 456789);dic.Add("Name", "字典用法");dic.Add("CreateTime", DateTime.Now);dic.Add("Isdeleted", 1);dictionaryList.Add(dic);DataTableResult tableResult = db.Storageable(dictionaryList, "StudentInfo").WhereColumns("id").ToStorage();//id作为主键tableResult.AsInsertable.ExecuteCommand();//如果是自增要添加IgnoreColumnsdictionaryList[0]["Name"] = "修改名称了";DataTableResult tableResult1 = db.Storageable(dictionaryList, "StudentInfo").WhereColumns("id").ToStorage();//id作为主键tableResult1.AsUpdateable.ExecuteCommand();}//分页处理{List<StudentInfo> list = db.Queryable<StudentInfo>().ToList();//分页处理db.Utilities.PageEach(list, 2000, pageList =>{ db.Storageable(pageList).ExecuteCommand();//条件列禁止varchar(50)以上,并且是主键或者有索引为佳 //也可以用BulkCopy//var x= db.Storageable<Order>(data).ToStorage();//x.BulkCopy();//x.BulkUpdate(); });}}
}
3.6、单表基本查询
查询集合
查询总数
按条件查询
多条件查询
动态OR查询
模糊查询
主键查询
查询第一条
查前几条
是否存在记录
In查询/Not In
排序
In的模糊查询
多个字段 条件拼接
ConnectionConfig connectionConfig = new ConnectionConfig()
{ConnectionString = CustomConnectionConfig.ConnectionString001,IsAutoCloseConnection = true,DbType = DbType.SqlServer
};
using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
{db.Aop.OnLogExecuting = (s, p) =>{Console.WriteLine("----------------------------");Console.WriteLine($"Sql语句:{s}");};List<StudentInfo> addlist = new List<StudentInfo>();for (int i = 0; i < 500; i++){addlist.Add(new StudentInfo(){Id = i + 1,CreateTime = DateTime.Now,Isdeleted = false,Name = $"名称_{i + 1}",SchoolId = i + 1,});}db.Deleteable<StudentInfo>().ExecuteCommand();db.Insertable<StudentInfo>(addlist).ExecuteCommand();//查询集合-//select * from StudentInfoList<StudentInfo> list = db.Queryable<StudentInfo>().ToList();//查询总数int count = db.Queryable<StudentInfo>().Count();//select count(1) from StudentInfoList<StudentInfo> studentList;//按条件查询{studentList = db.Queryable<StudentInfo>().Where(it => it.Id == 1).ToList();//select * from StudentInfo where id=1studentList = db.Queryable<StudentInfo>().Where(it => it.Name != null).ToList();//不是null//select * from StudentInfo where name is not nullstudentList = db.Queryable<StudentInfo>().Where(it => it.Name == null).ToList();//是null //select * from StudentInfo where name is nullstudentList = db.Queryable<StudentInfo>().Where(it => it.Name != "名称_11").ToList();//不是空 ,不为空 //select * from StudentInfo where name <> ''}//多条件查询 {studentList = db.Queryable<StudentInfo>().Where(it => it.Id > 10 && it.Name == "名称_11").ToList();//select * from StudentInfo where id>10 and name='a'studentList = db.Queryable<StudentInfo>().Where(it => it.Id > 10).Where(it => it.Name == "名称_11").ToList();}//动态OR查询{Expressionable<StudentInfo> exp = Expressionable.Create<StudentInfo>();string name = "名称_11";//.OrIf 是条件成立才会拼接ORexp.OrIF(!string.IsNullOrWhiteSpace(name), it => it.Name.Contains(name));//拼接ORexp.Or(it => it.Name.Contains("名称_"));studentList = db.Queryable<StudentInfo>().Where(exp.ToExpression()).ToList();}//模糊查询{studentList = db.Queryable<StudentInfo>().Where(it => it.Name.Contains("名称_")).ToList();//select * from StudentInfo where name like %jack%}//根据主键查询{/*单主键查询*///通过主键查询 SingleByIddb.Queryable<StudentInfo>().InSingle(2);//根据ID查询//select * from StudentInfo where id=2db.Queryable<StudentInfo>().Single(it => it.Id == 2);/*多主键查询*/var getAll = db.Queryable<StudentInfo>().WhereClassByPrimaryKey(new StudentInfo() { Id = 123 }).ToList(); //单个实体 getAll = db.Queryable<StudentInfo>().WhereClassByPrimaryKey(new List<StudentInfo>(){new StudentInfo() { Id = 123 },new StudentInfo() { Id = 234 },new StudentInfo() { Id = 345 }}).ToList(); //支持集合}//查询第一条 ,第一行{//First() 等同于C#中的 FirstOrDefault , 没有值返回 null//没有返回NullStudentInfo student = db.Queryable<StudentInfo>().First(it => it.Id == 1);}{//没有返回Null//select top 1 * from StudentInfo order by id desc where id=1StudentInfo student = db.Queryable<StudentInfo>().OrderBy(it => it.Id, OrderByType.Desc).First(it => it.Id == 1);}//查前几条 {List<StudentInfo> studetntlist = db.Queryable<StudentInfo>().Take(10).ToList();}//数据行数{int count1 = db.Queryable<StudentInfo>().Where(it => it.Id > 11).Count();//同步Task<int> countTask = db.Queryable<StudentInfo>().Where(it => it.Id > 11).CountAsync();//异步//select count(*) from StudentInfo where id>11//你也可以用函数//SqlFunc.AggregateCount}//是否存在记录{db.Close();db.Open();bool isExists = db.Queryable<StudentInfo>().Where(it => it.Id > 11).Any();isExists = db.Queryable<StudentInfo>().Any(it => it.Id > 11); //上面语法的简化}//In查询,IN的使用{int[] allIds = new int[] { 2, 3, 31 };List<StudentInfo> list1 = db.Queryable<StudentInfo>().Where(it => allIds.Contains(it.Id)).ToList();//字符串类型 varchar和nvarchar (默认varchar来保证性能)//NameList.Contains(it.Name, true) //true和false来控制是varchar还是nvarchar}//多个字段 条件拼接{List<StudentInfo> OrderList = new List<StudentInfo>(){new StudentInfo{ Id = 1,Name="名称_1"},new StudentInfo{ Id = 2,Name="名称_2"},new StudentInfo{ Id = 3,Name="名称_3"}};Expressionable<StudentInfo> exp = new Expressionable<StudentInfo>();foreach (var item in OrderList){exp.Or(it => it.Id == item.Id && it.Name == item.Name);}//使用构造好的表达式var studentlist = db.Queryable<StudentInfo>().Where(exp.ToExpression()).ToList();}//使用 in 的模糊查询{var names = new string[] { "名称_", "名称_11" };Expressionable<StudentInfo> exp = new Expressionable<StudentInfo>();foreach (var item in names){exp.Or(it => it.Name.Contains(item));}var studentlist = db.Queryable<StudentInfo>().Where(exp.ToExpression()).ToList();}//NOT IN{int[] allIds = new int[] { 2, 3, 31 };var studentlist = db.Queryable<StudentInfo>().Where(it => !allIds.Contains(it.Id)).ToList();}//简单排序{var studentlist = db.Queryable<StudentInfo>().OrderBy(st => st.Id, OrderByType.Desc).ToList();}//查询一列{//单值 查询列 查询单独列var studentlist = db.Queryable<StudentInfo>().Select(it => it.Name).ToList();}//查询单条{StudentInfo student = db.Queryable<StudentInfo>().Single(it => it.Id == 1);//没有返回Null,如果结果大于1条会抛出错误//select * from StudentInfo where id=1 // 查询id等于1的单条记录}//获取最大值,最小值{int maxNum = db.Queryable<StudentInfo>().Max(it => it.Id);//同步 Task<int> maxTask = db.Queryable<StudentInfo>().MaxAsync(it => it.Id);//异步db.Close();db.Open();int minNum = db.Queryable<StudentInfo>().Min(it => it.Id);//同步Task<int> minTask = db.Queryable<StudentInfo>().MinAsync(it => it.Id);//异步}//求和{db.Close();db.Open();int sumNum = db.Queryable<StudentInfo>().Sum(it => it.Id);//同步Task<int> sumTask = db.Queryable<StudentInfo>().SumAsync(it => it.Id);//异步}//查询过滤排除某一个字段{/***单表***/db.Close();db.Open();db.Queryable<StudentInfo>().ToList();db.Queryable<StudentInfo>().IgnoreColumns(it => it.Name).ToList();//只支持单表查询 }
}
3.7、连接查询
左连接查询
右连接查询
内连接查询
全连接查询
并集查询
准备数据
[SugarTable("User")]//
public class User
{[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//数据库是自增才配自增 public int Id { get; set; }[SugarColumn(ColumnName = "CompanyId", IsNullable = true)]public int? CompanyId { get; set; }[Navigate(NavigateType.ManyToOne, nameof(CompanyId))]public Company? CompanyInfo { get; set; }[SugarColumn(ColumnName = "UserName", IsNullable = true)]//数据库与实体不一样设置列名 public string? UserName { get; set; }[SugarColumn(ColumnName = "CreateTime", IsNullable = true)]public DateTime? CreateTime { get; set; }public int UserDetailId { get; set; }[Navigate(NavigateType.OneToOne, nameof(UserDetailId))]public UserDetail? UserDetailInfo { get; set; } //不能赋值只能是null[Navigate(typeof(UserRoleMapping), nameof(UserRoleMapping.UserId), nameof(UserRoleMapping.RoleId))]//注意顺序public List<Role> RoleList { get; set; } //不能赋值只能是null
}public class Company{[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]public int Id { get; set; }public string? CompanyName { get; set; }public DateTime CreateTime { get; set; }[Navigate(NavigateType.OneToMany, nameof(User.CompanyId))]public List<User>? UserList { get; set; }}
[SugarTable("UserScore")]//
public class UserScore
{[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]public int Id { get; set; }public int UserId { get; set; }/// <summary>/// 考核指标/// </summary>public string? Subject { get; set; }/// <summary>/// 考核成绩/// </summary>public int Achievement { get; set; }public DateTime? CreateTime { get; set; }}
代码
/// <summary>
/// 连接查询--必然涉及到有多个表
/// </summary>
public static void LinkQueryShow()
{ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = CustomConnectionConfig.ConnectionString001,IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){db.CodeFirst.InitTables<Company>();db.CodeFirst.InitTables<User>();db.CodeFirst.InitTables<UserScore>();db.Deleteable<UserScore>().ExecuteCommand();db.Deleteable<Company>().ExecuteCommand();db.Deleteable<User>().ExecuteCommand();List<Company> companyList = new List<Company>();for (int i = 0; i < 3; i++){companyList.Add(new Company(){CreateTime = DateTime.Now,Id = i + 1,CompanyName = $"朝夕教育_{i + 1}"});}db.Insertable<Company>(companyList).ExecuteCommand();List<User> userList = new List<User>();List<UserScore> userScoreList = new List<UserScore>();for (int i = 0; i < 10; i++){userList.Add(new User(){CreateTime = DateTime.Now,Id = i + 1,UserName = $"用户_{i + 1}",CompanyId = companyList[0].Id});userScoreList.Add(new UserScore(){UserId = i + 1,Subject = "考勤",Achievement = 90,CreateTime = DateTime.Now});userScoreList.Add(new UserScore(){UserId = i + 1,Subject = "绩效",Achievement = 90,CreateTime = DateTime.Now});userScoreList.Add(new UserScore(){UserId = i + 1,Subject = "项目奖金",Achievement = 89,CreateTime = DateTime.Now});}db.Insertable<User>(userList).ExecuteCommand();db.Insertable<UserScore>(userScoreList).ExecuteCommand();//配置生成sql语句{db.Aop.OnLogExecuting = (s, p) =>{Console.WriteLine("----------------------------");Console.WriteLine($"Sql语句:{s}");};}//左连接{var query1 = db.Queryable<Company>().LeftJoin<User>((c, u) => c.Id == u.CompanyId).LeftJoin<UserScore>((c, u, us) => u.Id == us.UserId).Where(c => c.Id == 1).Select((c, u, us) => new{CompanyId = c.Id,CompanyName = c.CompanyName,UserNae = u.UserName,Subject = us.Subject,ScoreCoutn = us.Achievement}).ToList();var query2 = db.Queryable<Company, User, UserScore>((c, u, us) =>new JoinQueryInfos(JoinType.Left, c.Id == u.CompanyId, JoinType.Left, u.Id == us.UserId)).Where(c => c.Id == 1).Select((c, u, us) => new{CompanyId = c.Id,CompanyName = c.CompanyName,UserNae = u.UserName,Subject = us.Subject,ScoreCoutn = us.Achievement}).ToList();}//右链接{var query1 = db.Queryable<Company>().RightJoin<User>((c, u) => c.Id == u.CompanyId).RightJoin<UserScore>((c, u, us) => u.Id == us.UserId).Where(c => c.Id == 1).Select((c, u, us) => new{CompanyId = c.Id,CompanyName = c.CompanyName,UserNae = u.UserName,Subject = us.Subject,ScoreCoutn = us.Achievement}).ToList();var query2 = db.Queryable<Company, User, UserScore>((c, u, us) =>new JoinQueryInfos(JoinType.Right, c.Id == u.CompanyId, JoinType.Right, u.Id == us.UserId)).Where(c => c.Id == 1).Select((c, u, us) => new{CompanyId = c.Id,CompanyName = c.CompanyName,UserNae = u.UserName,Subject = us.Subject,ScoreCoutn = us.Achievement}).ToList();}//内连接{var query1 = db.Queryable<Company>().InnerJoin<User>((c, u) => c.Id == u.CompanyId).InnerJoin<UserScore>((c, u, us) => u.Id == us.UserId).Where(c => c.Id == 1).Select((c, u, us) => new{CompanyId = c.Id,CompanyName = c.CompanyName,UserNae = u.UserName,Subject = us.Subject,ScoreCoutn = us.Achievement}).ToList();var query2 = db.Queryable<Company, User, UserScore>((c, u, us) =>new JoinQueryInfos(JoinType.Inner, c.Id == u.CompanyId, JoinType.Inner, u.Id == us.UserId)).Where(c => c.Id == 1).Select((c, u, us) => new{CompanyId = c.Id,CompanyName = c.CompanyName,UserNae = u.UserName,Subject = us.Subject,ScoreCoutn = us.Achievement}).ToList();}//全连接{var query1 = db.Queryable<Company>().FullJoin<User>((c, u) => c.Id == u.CompanyId).FullJoin<UserScore>((c, u, us) => u.Id == us.UserId).Where(c => c.Id == 1).Select((c, u, us) => new{CompanyId = c.Id,CompanyName = c.CompanyName,UserNae = u.UserName,Subject = us.Subject,ScoreCoutn = us.Achievement}).ToList();var query2 = db.Queryable<Company, User, UserScore>((c, u, us) =>new JoinQueryInfos(JoinType.Full, c.Id == u.CompanyId, JoinType.Full, u.Id == us.UserId)).Where(c => c.Id == 1).Select((c, u, us) => new{CompanyId = c.Id,CompanyName = c.CompanyName,UserNae = u.UserName,Subject = us.Subject,ScoreCoutn = us.Achievement}).ToList();}//并集{var q1 = db.Queryable<Student>().Select(it => new User { UserName = it.Name });var q2 = db.Queryable<User>().Select(it => new User { UserName = it.UserName });var list = db.UnionAll(q1, q2).ToList();}};
}
3.8、复杂查询
分组聚合
Distinct关键字
开窗函数
合并结合
分页查询
Order排序
/// <summary>/// 复杂查询/// </summary>public static void ComplexQueryShow(){ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = CustomConnectionConfig.ConnectionString001,IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){//配置生成sql语句{db.Aop.OnLogExecuting = (s, p) =>{Console.WriteLine("----------------------------");Console.WriteLine($"Sql语句:{s}");};}//分组聚合{var list = db.Queryable<Student>().GroupBy(it => new { it.Id, it.Name }).Having(it => SqlFunc.AggregateAvg(it.Id) > 0).Select(it => new{idAvg = SqlFunc.AggregateAvg(it.Id),count = SqlFunc.AggregateCount(it.Id),name = it.Name}).ToList();}//一般用来指定字段去重复,查询不重复的值,去重字段{var list = db.Queryable<Student>().Distinct().Select(it => new { it.Name }).ToList();}//开窗函数{var model = db.Queryable<Student>().Take(1).PartitionBy(it => it.Name).ToList();var model1 = db.Queryable<Student>().OrderBy(it => it.Id, OrderByType.Desc).Take(1).PartitionBy(it => it.Name).ToList();}//合并结合{var test48 = db.Queryable<Student>().Select(it => new{index2 = SqlFunc.RowNumber(it.Id, it.Name),name = it.Name,date = it.CreateTime}).MergeTable()//将结果合并成一个表.Where(it => it.index2 == 1).ToList();}//分页查询{{int pagenumber = 2; // pagenumber是从1开始的不是从零开始的int pageSize = 2;int totalCount = 0;//单表分页var page = db.Queryable<Student>().ToPageList(pagenumber, pageSize, ref totalCount);var page1 = db.Queryable<Student>().ToOffsetPage(pagenumber, pageSize, ref totalCount);}//如果SqlServer不想有Rownumber可以用 ToOffsetPage 较新版本支持 //多表分页{int pagenumber = 1; // pagenumber是从1开始的不是从零开始的int pageSize = 20;int totalCount = 0;var list = db.Queryable<Company>().LeftJoin<User>((c, u) => c.Id == u.CompanyId).Select((c, u) => new{Id = c.Id,cName = c.CompanyName,uId = u.Id,uName = u.UserName}).ToOffsetPage(pagenumber, pageSize, ref totalCount);}//异步分页{int pagenumber = 1; // pagenumber是从1开始的不是从零开始的int pageSize = 20;int totalCount = 0;RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解Task<List<Student>> studentTask =db.Queryable<Student>().ToPageListAsync(pagenumber, pageSize, total);//ToPageAsync List<Student> list = studentTask.Result;}}//Order排序{var list = db.Queryable<Company, User>((c, u) => new JoinQueryInfos(JoinType.Left, c.Id == u.CompanyId)).OrderBy(c => c.Id)//升序.OrderBy((c, u) => c.CompanyName, OrderByType.Desc)//倒序 .Select((c, u) => new{cId = c.Id,cName = c.CompanyName,uId = u.Id,uName = u.UserName}).ToList();}//多个Order一起{var list = db.Queryable<User>().OrderBy(it => new{it.Id,name = SqlFunc.Desc(it.UserName)}).ToList();}//动态排序{//通过类中属性名获取数据库字段名{var orderByFieldName = db.EntityMaintenance.GetDbColumnName<User>("Id");//防注入var list = db.Queryable<Student>().OrderBy(orderByFieldName + " asc ").ToList(); ;}{var list = db.Queryable<Company, User>((c, u) => new JoinQueryInfos(JoinType.Left, c.Id == u.CompanyId)).OrderBy("c.id asc,u.Id desc ") //多表查询有别名(c&u) .Select((c, u) => new{cId = c.Id,cName = c.CompanyName,uId = u.Id,uName = u.UserName}).ToList();}{var pageJoin = db.Queryable<Company, User>((c, u) => new JoinQueryInfos(JoinType.Left, c.Id == u.CompanyId)).Select((c, u) => new{cId = c.Id,cName = c.CompanyName,uId = u.Id,uName = u.UserName}).MergeTable()//将查询结果集变成表MergeTable.Where(it => it.cId == 1).OrderBy("cName asc").ToList();//对表MergeTable进行排序}//随机排序取10条{db.Queryable<Student>().Take(10).OrderBy(st => SqlFunc.GetRandom()).ToList();}}}}
3.9、导航属性
导航属性是 实体类型 上的可选属性,它允许从 关联 的 一端 导航到另一端。 与其他 属性 不同,导航属
性并不携带数据。
关系型数据库--保存数据--保存数据之间的关系;
表关系:一对一关系 一个人---对应一个身份证号 一夫一妻
一对多关系 一个老师带多个学生 公司有多个员工
多对多关系 课程和学员,一个学员可以学习多个课程 一个课程可以让多个学员来学
习,
用户角色关系
补充:动态导航,在程序中可以不用配置关联字段,在查询的过程中,把需要关联的字段,手动匹配完
成导航查询;
补充: 多对一关系。
准备
public enum NavigateType
{OneToOne = 1,OneToMany,ManyToOne,ManyToMany,Dynamic
}
///NavigateType.OneToOne[SugarTable("User")]// public class User{[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//数据库是自增才配自增 public int Id { get; set; }[SugarColumn(ColumnName = "CompanyId", IsNullable = true)]public int? CompanyId { get; set; }[Navigate(NavigateType.ManyToOne, nameof(CompanyId))]public Company? CompanyInfo { get; set; }[SugarColumn(ColumnName = "UserName", IsNullable = true)]//数据库与实体不一样设置列名 public string? UserName { get; set; }[SugarColumn(ColumnName = "CreateTime", IsNullable = true)]public DateTime? CreateTime { get; set; }public int UserDetailId { get; set; }[Navigate(NavigateType.OneToOne, nameof(UserDetailId))]public UserDetail? UserDetailInfo { get; set; } //不能赋值只能是null[Navigate(typeof(UserRoleMapping), nameof(UserRoleMapping.UserId), nameof(UserRoleMapping.RoleId))]//注意顺序public List<Role> RoleList { get; set; } //不能赋值只能是null}public class StudentA{[SugarColumn(IsPrimaryKey = true)]public int StudentId { get; set; }public string? Name { get; set; }public int SchoolId { get; set; }[SugarColumn(IsIgnore = true)]public SchoolA SchoolA { get; set; }[Navigate(NavigateType.Dynamic, null)] //自定义关系映射public List<BookA> Books { get; set; } //只能是null 不能赋默认值 }public class BookA{[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]public int BookId { get; set; }public string? Name { get; set; }public int studenId { get; set; }}public class SchoolA{[SugarColumn(IsPrimaryKey = true)]public int SchoolId { get; set; }public string? SchoolName { get; set; }[SugarColumn(IsIgnore = true)]public List<RoomA> RoomList { get; set; }[SugarColumn(IsIgnore = true)]public List<TeacherA> TeacherList { get; set; }}public class TeacherA{[SugarColumn(IsPrimaryKey = true)]public int Id { get; set; }public int SchoolId { get; set; }public string? Name { get; set; }}public class RoomA{[SugarColumn(IsPrimaryKey = true)]public int RoomId { get; set; }public string? RoomName { get; set; }public int SchoolId { get; set; }}
/// <summary>
/// 导航属性
/// </summary>
public static void NavigationPropertiesShow()
{ConnectionConfig connectionConfig = new ConnectionConfig(){ConnectionString = CustomConnectionConfig.ConnectionString001,IsAutoCloseConnection = true,DbType = DbType.SqlServer};using (SqlSugarClient db = new SqlSugarClient(connectionConfig)){{db.Aop.OnLogExecuting = (s, p) =>{Console.WriteLine("----------------------------");Console.WriteLine($"Sql语句:{s}");};}#region 一对一关系 {if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("UserDetail", false)){db.DbMaintenance.DropTable<UserDetail>();}db.CodeFirst.InitTables<User>();db.CodeFirst.InitTables<UserDetail>();db.DeleteNav<User>(c => c.Id > 0).Include(c => c.UserDetailInfo).ExecuteCommand();List<User> users = new List<User>(){new User(){CompanyId = 1,UserName = "Richard",CreateTime = DateTime.Now,UserDetailInfo = new UserDetail(){Address = "湖北武汉",Description = ".NET金牌讲师"}},new User(){CompanyId = 1,UserName = "cole老师号",CreateTime = DateTime.Now,UserDetailInfo = new UserDetail(){Address = "湖北黄冈",Description = "金牌助教"}}};//导航属性新增bool bResult = db.InsertNav(users).Include(z1 => z1.UserDetailInfo).ExecuteCommand();//导航属性查询 var list1 = db.Queryable<User>().Includes(t => t.UserDetailInfo) //多层级 .ToList();var list2 = db.Queryable<User>().Includes(t => t.UserDetailInfo) //多层级 .Where(c => c.UserName == "Richard").ToList();list2[0].UserName = "Richard老师";list2[0].UserDetailInfo.Address = "湖北武汉汉阳";bool bResult1 = db.UpdateNav(list2).Include(u => u.UserDetailInfo).ExecuteCommand();bool bResult2 = db.DeleteNav<User>(list2).Include(c => c.UserDetailInfo).ExecuteCommand();}#endregion#region 一对多关系 {if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("Company", false)){db.DbMaintenance.DropTable<Company>();}db.CodeFirst.InitTables<Company>();db.CodeFirst.InitTables<User>();//导航删除db.DeleteNav<Company>(c => c.Id > 0).Include(c => c.UserList).ExecuteCommand();List<Company> companies = new List<Company>(){new Company(){CompanyName="朝夕教育",CreateTime= DateTime.Now,UserList=new List<User>(){new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Eleven"},new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Richard",UserDetailInfo=new UserDetail{Address="湖北武汉汉阳",Description="金牌讲师"}},new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Gerry"}}},new Company(){CompanyName="腾讯课堂",CreateTime= DateTime.Now,}};//导航新增db.InsertNav(companies).Include(c => c.UserList).ExecuteCommand();//一对多导航查询var list = db.Queryable<Company>().Includes(t => t.UserList).ToList();var userlist = db.Queryable<User>().Includes(u => u.CompanyInfo).ToList();var list1 = db.Queryable<Company>().Includes(x => x.UserList.Where(u => u.UserName == "Richard").ToList()).Where(x => x.CompanyName.Contains("朝夕教育")).ToList();list1[0].CompanyName = "朝夕教育-金牌机构";list1[0].UserList[0].UserName = "Richard老师";//修改bool bResult2 = db.UpdateNav(list1).Include(u => u.UserList).ExecuteCommand();///删除bool bResult3 = db.DeleteNav(list1).Include(u => u.UserList).ExecuteCommand();}#endregion#region 多对多关系 {if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("Role", false)){db.DbMaintenance.DropTable<Role>();}if (db.DbMaintenance.IsAnyTable("UserRoleMapping", false)){db.DbMaintenance.DropTable<UserRoleMapping>();}db.CodeFirst.InitTables<User>();db.CodeFirst.InitTables<Role>();db.CodeFirst.InitTables<UserRoleMapping>();List<User> users = new List<User>(){new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Richard老师",RoleList=new List<Role>(){new Role(){CreateTime= DateTime.Now,RoleName="管理员"},new Role(){CreateTime= DateTime.Now,RoleName="金牌讲师"}}}};db.InsertNav(users).Include(u => u.RoleList)// 插入第一层 SchoolA .ExecuteCommand();var list1 = db.Queryable<User>().Includes(x => x.RoleList).ToList();var list2 = db.Queryable<User>().Includes(x => x.RoleList.Where(r => r.RoleName == "管理员").ToList()).Where(c => c.UserName.Equals("Richard老师")).ToList();bool bResult = db.UpdateNav(list2).Include(u => u.RoleList).ExecuteCommand();bool bResult1 = db.DeleteNav(list1).Include(u => u.RoleList).ExecuteCommand();int iResult1 = db.Deleteable(list1).ExecuteCommand();var roles = db.Queryable<Role>().ToList();int iResult2 = db.Deleteable(roles).ExecuteCommand();}#endregion#region 手动、指定字段、多字段{if (db.DbMaintenance.IsAnyTable("StudentA", false)){db.DbMaintenance.DropTable<StudentA>();}if (db.DbMaintenance.IsAnyTable("BookA", false)){db.DbMaintenance.DropTable<BookA>();}db.CodeFirst.InitTables<StudentA>();db.CodeFirst.InitTables<BookA>();List<StudentA> studentAs = new List<StudentA>(){new StudentA(){StudentId= 1,Name="张三同学",}};List<BookA> bookAs = new List<BookA>(){new BookA(){studenId= 1,Name="语文",},new BookA(){studenId= 1,Name="数学",}};db.Insertable(studentAs).ExecuteCommand();db.Insertable(bookAs).ExecuteCommand();var list = db.Queryable<StudentA>().Includes(it => it.Books.MappingField(z => z.studenId, () => it.StudentId).Where(z => z.BookId == 1).ToList()).ToList();}#endregion#region 性能优化,{if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("Company", false)){db.DbMaintenance.DropTable<Company>();}db.CodeFirst.InitTables<Company>();db.CodeFirst.InitTables<User>();//导航删除db.DeleteNav<Company>(c => c.Id > 0).Include(c => c.UserList).ExecuteCommand();List<Company> companies = new List<Company>();for (int i = 0; i < 5000; i++){Company company = new Company(){CompanyName = $"朝夕教育_{i}",CreateTime = DateTime.Now};List<User> userlist = new List<User>();for (int j = 0; j < 10; j++){User user = new User(){CompanyId = 1,CreateTime = DateTime.Now,UserName = $"学员_{j}"};userlist.Add(user);}company.UserList = userlist;companies.Add(company);}db.InsertNav<Company>(companies).Include(c => c.UserList).ExecuteCommand();Console.WriteLine("====================================================================");Console.WriteLine("====================================================================");Console.WriteLine("====================================================================");Console.WriteLine("====================================================================");Console.WriteLine("====================================================================");List<Company> resultList = new List<Company>();db.Queryable<Company>().Includes(it => it.UserList).ForEach(it => resultList.Add(it), 300); //每次查询300条}#endregion#region 数据映射{AutoMapper List<Company> companies = db.Queryable<Company>().Includes(it => it.UserList).ToList(); //每次查询300条 List<CompanyDto> dtoList = companies.Adapt<List<CompanyDto>>();}#endregion#region 导航方法{if (db.DbMaintenance.IsAnyTable("Company", false)){db.DbMaintenance.DropTable<Company>();}if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("UserDetail", false)){db.DbMaintenance.DropTable<UserDetail>();}db.CodeFirst.InitTables<Company>();db.CodeFirst.InitTables<User>();db.CodeFirst.InitTables<UserDetail>();List<Company> companies = new List<Company>(){new Company(){CompanyName="朝夕教育",CreateTime= DateTime.Now,UserList=new List<User>(){new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Eleven"},new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Richard",UserDetailInfo=new UserDetail{Address="湖北武汉汉阳",Description="金牌讲师"}},new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Gerry"}}},new Company(){CompanyName="腾讯课堂",CreateTime= DateTime.Now,}};//导航新增db.InsertNav(companies).Include(c => c.UserList).ThenInclude(u => u.UserDetailInfo).ExecuteCommand();Console.WriteLine("================================");List<Company> companyList1 = db.Queryable<Company>()//.Where(c=>c.UserList.Count()>0).Where(it => it.UserList.Any()).ToList();List<Company> companyList2 = db.Queryable<Company>().Where(it => it.UserList.Any(c => c.UserName.Equals("Richard"))).ToList();if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("UserDetail", false)){db.DbMaintenance.DropTable<UserDetail>();}db.CodeFirst.InitTables<User>();db.CodeFirst.InitTables<UserDetail>();db.DeleteNav<User>(c => c.Id > 0).Include(c => c.UserDetailInfo).ExecuteCommand();List<User> users = new List<User>(){new User(){CompanyId = 1,UserName = "Richard",CreateTime = DateTime.Now,UserDetailInfo = new UserDetail(){Address = "湖北武汉",Description = ".NET金牌讲师"}},new User(){CompanyId = 1,UserName = "cole老师号",CreateTime = DateTime.Now,UserDetailInfo = new UserDetail(){Address = "湖北黄冈",Description = "金牌助教"}}};db.InsertNav(users).Include(c => c.CompanyInfo).ExecuteCommand();List<User> userlist = db.Queryable<User>().Where(x => SqlFunc.Exists(x.UserDetailInfo.Id)).ToList();}#endregion#region 联表导航{Console.WriteLine("================联表导航=====================");if (db.DbMaintenance.IsAnyTable("StudentA", false)){db.DbMaintenance.DropTable<StudentA>();}if (db.DbMaintenance.IsAnyTable("RoomA", false)){db.DbMaintenance.DropTable<RoomA>();}if (db.DbMaintenance.IsAnyTable("SchoolA", false)){db.DbMaintenance.DropTable<SchoolA>();}if (db.DbMaintenance.IsAnyTable("TeacherA", false)){db.DbMaintenance.DropTable<TeacherA>();}db.CodeFirst.InitTables<StudentA, RoomA, SchoolA, TeacherA>();db.DbMaintenance.TruncateTable<StudentA>();db.DbMaintenance.TruncateTable<RoomA>();db.DbMaintenance.TruncateTable<SchoolA>();db.DbMaintenance.TruncateTable<TeacherA>();db.Insertable(new RoomA() { RoomId = 1, RoomName = "北大001室", SchoolId = 1 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 2, RoomName = "北大002室", SchoolId = 1 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 3, RoomName = "北大003室", SchoolId = 1 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 4, RoomName = "清华001厅", SchoolId = 2 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 5, RoomName = "清华002厅", SchoolId = 2 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 6, RoomName = "清华003厅", SchoolId = 2 }).ExecuteCommand();db.Insertable(new SchoolA() { SchoolId = 1, SchoolName = "北大" }).ExecuteCommand();db.Insertable(new SchoolA() { SchoolId = 2, SchoolName = "清华" }).ExecuteCommand();db.Insertable(new StudentA() { StudentId = 1, SchoolId = 1, Name = "北大jack" }).ExecuteCommand();db.Insertable(new StudentA() { StudentId = 2, SchoolId = 1, Name = "北大tom" }).ExecuteCommand();db.Insertable(new StudentA() { StudentId = 3, SchoolId = 2, Name = "清华jack" }).ExecuteCommand();db.Insertable(new StudentA() { StudentId = 4, SchoolId = 2, Name = "清华tom" }).ExecuteCommand();db.Insertable(new TeacherA() { SchoolId = 1, Id = 1, Name = "北大老师01" }).ExecuteCommand();db.Insertable(new TeacherA() { SchoolId = 1, Id = 2, Name = "北大老师02" }).ExecuteCommand();db.Insertable(new TeacherA() { SchoolId = 2, Id = 3, Name = "清华老师01" }).ExecuteCommand();db.Insertable(new TeacherA() { SchoolId = 2, Id = 4, Name = "清华老师02" }).ExecuteCommand();Console.WriteLine("=================================================");var list = db.Queryable<StudentA>().ToList();//这儿也可以联表查询//var list1 = db.Queryable<StudentA>().Includes(c=>c.SchoolA).ToList();//这儿也可以联表查询db.ThenMapper(list, stu =>{//如果加Where不能带有stu参数,stu参数写到 SetContextstu.SchoolA = db.Queryable<SchoolA>().SetContext(scl => scl.SchoolId, () => stu.SchoolId, stu).FirstOrDefault();});}#endregion#region 实现无限层--树 {if (db.DbMaintenance.IsAnyTable("Tree", false)){db.DbMaintenance.DropTable<Tree>();}db.CodeFirst.InitTables<Tree>();Tree tree = new Tree(){Id = 1,Name = "一级树",ParentId = 0,Child = new List<Tree>{new Tree(){ParentId=1,Id = 5,Name="二级目录-1",Child=new List<Tree>{new Tree() {Id = 6,Name="三级目录-1",ParentId=2,Child=new List<Tree>{new Tree() {Id = 7,ParentId=6,Name="四级目录-1"}}}}}}};db.InsertNav<Tree>(tree).Include(it => it.Child).ThenInclude(c => c.Child).ThenInclude(c1 => c1.Child).ThenInclude(c2 => c2.Child).ExecuteCommand();var treeRoot = db.Queryable<Tree>().Where(it => it.Id == 1).ToList();//第一层db.ThenMapper(treeRoot, item =>{item.Child = db.Queryable<Tree>().SetContext(x => x.ParentId, () => item.Id, item).ToList();});//第二层db.ThenMapper(treeRoot.SelectMany(it => it.Child), it =>{it.Child = db.Queryable<Tree>().SetContext(x => x.ParentId, () => it.Id, it).ToList();});//第三层db.ThenMapper(treeRoot.SelectMany(it => it.Child).SelectMany(it => it.Child), it =>{it.Child = db.Queryable<Tree>().SetContext(x => x.ParentId, () => it.Id, it).ToList();});List<Tree> list = db.Queryable<Tree>().ToTree(it => it.Child, it => it.ParentId, 0);}#endregion }
}
3.10、导航属性性能优化
db.ThenMapper(list, stu =>
{
//如果加Where不能带有stu参数,stu参数写到 SetContext
stu.SchoolA = db.Queryable<SchoolA>().SetContext(scl => scl.SchoolId, () =>
stu.SchoolId, stu).FirstOrDefault();
//可以联查询的
//stu.xxxx=db.Queryable<SchoolA>().LeftJoin<XXX>
().Select(xxxx).SetContext(....).ToList();
});
#region 性能优化,
{if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("Company", false)){db.DbMaintenance.DropTable<Company>();}db.CodeFirst.InitTables<Company>();db.CodeFirst.InitTables<User>();//导航删除db.DeleteNav<Company>(c => c.Id > 0).Include(c => c.UserList).ExecuteCommand();List<Company> companies = new List<Company>();for (int i = 0; i < 5000; i++){Company company = new Company(){CompanyName = $"朝夕教育_{i}",CreateTime = DateTime.Now};List<User> userlist = new List<User>();for (int j = 0; j < 10; j++){User user = new User(){CompanyId = 1,CreateTime = DateTime.Now,UserName = $"学员_{j}"};userlist.Add(user);}company.UserList = userlist;companies.Add(company);}db.InsertNav<Company>(companies).Include(c => c.UserList).ExecuteCommand();Console.WriteLine("====================================================================");Console.WriteLine("====================================================================");Console.WriteLine("====================================================================");Console.WriteLine("====================================================================");Console.WriteLine("====================================================================");List<Company> resultList = new List<Company>();db.Queryable<Company>().Includes(it => it.UserList).ForEach(it => resultList.Add(it), 300); //每次查询300条
}#endregion
导航属性,分段查询 如果数据库中数据量偏大,且查询的数据量偏大,可以分段查询,一次查询多少条,继续往后执行查询
多少条;
3.11、查询映射
数据库中返回的数据是一个Model--实体-返回给客户端---User---UserDto---Autommper 对于大部分开发者,如果需要做集合的映射,实体映射,都会想到Automapper。
SqlSugar有一个工具:Mapster
nuget引入Mapster
List<Company> companies= db.Queryable<Company>()
.Includes(it => it.UserList)
.ToList(); //每次查询300条
var dtoList = companies.Adapt<List<CompanyDto>>();
#region 数据映射{AutoMapper List<Company> companies = db.Queryable<Company>().Includes(it => it.UserList).ToList(); //每次查询300条 List<CompanyDto> dtoList = companies.Adapt<List<CompanyDto>>();}#endregion
3.12、导航方法
Any
SqlFunc.Exists
List<Company> companyList1 = db.Queryable<Company>()
.Where(it => it.UserList.Any())
.ToList();
List<Company> companyList2 = db.Queryable<Company>()
.Where(it => it.UserList.Any(c => c.UserName.Equals("Richard")))
.ToList();
#region 导航方法{if (db.DbMaintenance.IsAnyTable("Company", false)){db.DbMaintenance.DropTable<Company>();}if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("UserDetail", false)){db.DbMaintenance.DropTable<UserDetail>();}db.CodeFirst.InitTables<Company>();db.CodeFirst.InitTables<User>();db.CodeFirst.InitTables<UserDetail>();List<Company> companies = new List<Company>(){new Company(){CompanyName="朝夕教育",CreateTime= DateTime.Now,UserList=new List<User>(){new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Eleven"},new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Richard",UserDetailInfo=new UserDetail{Address="湖北武汉汉阳",Description="金牌讲师"}},new User(){CompanyId=1,CreateTime= DateTime.Now,UserName="Gerry"}}},new Company(){CompanyName="腾讯课堂",CreateTime= DateTime.Now,}};//导航新增db.InsertNav(companies).Include(c => c.UserList).ThenInclude(u => u.UserDetailInfo).ExecuteCommand();Console.WriteLine("================================");List<Company> companyList1 = db.Queryable<Company>()//.Where(c=>c.UserList.Count()>0).Where(it => it.UserList.Any()).ToList();List<Company> companyList2 = db.Queryable<Company>().Where(it => it.UserList.Any(c => c.UserName.Equals("Richard"))).ToList();if (db.DbMaintenance.IsAnyTable("User", false)){db.DbMaintenance.DropTable<User>();}if (db.DbMaintenance.IsAnyTable("UserDetail", false)){db.DbMaintenance.DropTable<UserDetail>();}db.CodeFirst.InitTables<User>();db.CodeFirst.InitTables<UserDetail>();db.DeleteNav<User>(c => c.Id > 0).Include(c => c.UserDetailInfo).ExecuteCommand();List<User> users = new List<User>(){new User(){CompanyId = 1,UserName = "Richard",CreateTime = DateTime.Now,UserDetailInfo = new UserDetail(){Address = "湖北武汉",Description = ".NET金牌讲师"}},new User(){CompanyId = 1,UserName = "cole老师号",CreateTime = DateTime.Now,UserDetailInfo = new UserDetail(){Address = "湖北黄冈",Description = "金牌助教"}}};db.InsertNav(users).Include(c => c.CompanyInfo).ExecuteCommand();List<User> userlist = db.Queryable<User>().Where(x => SqlFunc.Exists(x.UserDetailInfo.Id)).ToList();}#endregion
3.13、ThenMapper方法使用
db.ThenMapper(list, stu =>
{
//如果加Where不能带有stu参数,stu参数写到 SetContext
stu.SchoolA = db.Queryable<SchoolA>().SetContext(scl => scl.SchoolId, () =>
stu.SchoolId, stu).FirstOrDefault();
//可以联查询的
//stu.xxxx=db.Queryable<SchoolA>().LeftJoin<XXX>
().Select(xxxx).SetContext(....).ToList();
});
#region 联表导航{Console.WriteLine("================联表导航=====================");if (db.DbMaintenance.IsAnyTable("StudentA", false)){db.DbMaintenance.DropTable<StudentA>();}if (db.DbMaintenance.IsAnyTable("RoomA", false)){db.DbMaintenance.DropTable<RoomA>();}if (db.DbMaintenance.IsAnyTable("SchoolA", false)){db.DbMaintenance.DropTable<SchoolA>();}if (db.DbMaintenance.IsAnyTable("TeacherA", false)){db.DbMaintenance.DropTable<TeacherA>();}db.CodeFirst.InitTables<StudentA, RoomA, SchoolA, TeacherA>();db.DbMaintenance.TruncateTable<StudentA>();db.DbMaintenance.TruncateTable<RoomA>();db.DbMaintenance.TruncateTable<SchoolA>();db.DbMaintenance.TruncateTable<TeacherA>();db.Insertable(new RoomA() { RoomId = 1, RoomName = "北大001室", SchoolId = 1 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 2, RoomName = "北大002室", SchoolId = 1 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 3, RoomName = "北大003室", SchoolId = 1 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 4, RoomName = "清华001厅", SchoolId = 2 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 5, RoomName = "清华002厅", SchoolId = 2 }).ExecuteCommand();db.Insertable(new RoomA() { RoomId = 6, RoomName = "清华003厅", SchoolId = 2 }).ExecuteCommand();db.Insertable(new SchoolA() { SchoolId = 1, SchoolName = "北大" }).ExecuteCommand();db.Insertable(new SchoolA() { SchoolId = 2, SchoolName = "清华" }).ExecuteCommand();db.Insertable(new StudentA() { StudentId = 1, SchoolId = 1, Name = "北大jack" }).ExecuteCommand();db.Insertable(new StudentA() { StudentId = 2, SchoolId = 1, Name = "北大tom" }).ExecuteCommand();db.Insertable(new StudentA() { StudentId = 3, SchoolId = 2, Name = "清华jack" }).ExecuteCommand();db.Insertable(new StudentA() { StudentId = 4, SchoolId = 2, Name = "清华tom" }).ExecuteCommand();db.Insertable(new TeacherA() { SchoolId = 1, Id = 1, Name = "北大老师01" }).ExecuteCommand();db.Insertable(new TeacherA() { SchoolId = 1, Id = 2, Name = "北大老师02" }).ExecuteCommand();db.Insertable(new TeacherA() { SchoolId = 2, Id = 3, Name = "清华老师01" }).ExecuteCommand();db.Insertable(new TeacherA() { SchoolId = 2, Id = 4, Name = "清华老师02" }).ExecuteCommand();Console.WriteLine("=================================================");var list = db.Queryable<StudentA>().ToList();//这儿也可以联表查询//var list1 = db.Queryable<StudentA>().Includes(c=>c.SchoolA).ToList();//这儿也可以联表查询db.ThenMapper(list, stu =>{//如果加Where不能带有stu参数,stu参数写到 SetContextstu.SchoolA = db.Queryable<SchoolA>().SetContext(scl => scl.SchoolId, () => stu.SchoolId, stu).FirstOrDefault();});}#endregion
3.14、ThenMapper查询树
var treeRoot = db.Queryable<Tree>().Where(it => it.Id == 1).ToList();
//第一层
db.ThenMapper(treeRoot, item =>
{
item.Child = db.Queryable<Tree>().SetContext(x => x.ParentId, () =>
item.Id, item).ToList();
});
//第二层
3.15、树操作
无需依赖导航属性
设置关联字段即可
public class Tree{[SugarColumn(IsPrimaryKey = true)]public int Id { get; set; }public string? Name { get; set; }public int ParentId { get; set; } //在树查询中Parentid 是特殊的;[SugarColumn(IsIgnore = true)][Navigate(NavigateType.OneToMany, nameof(ParentId))]//设置导航 一对一public List<Tree>? Child { get; set; }}
实现无限层--树
#region 实现无限层--树
{if (db.DbMaintenance.IsAnyTable("Tree", false)){db.DbMaintenance.DropTable<Tree>();}db.CodeFirst.InitTables<Tree>();Tree tree = new Tree(){Id = 1,Name = "一级树",ParentId = 0,Child = new List<Tree>{new Tree(){ParentId=1,Id = 5,Name="二级目录-1",Child=new List<Tree>{new Tree() {Id = 6,Name="三级目录-1",ParentId=2,Child=new List<Tree>{new Tree() {Id = 7,ParentId=6,Name="四级目录-1"}}}}}}};db.InsertNav<Tree>(tree).Include(it => it.Child).ThenInclude(c => c.Child).ThenInclude(c1 => c1.Child).ThenInclude(c2 => c2.Child).ExecuteCommand();var treeRoot = db.Queryable<Tree>().Where(it => it.Id == 1).ToList();//第一层db.ThenMapper(treeRoot, item =>{item.Child = db.Queryable<Tree>().SetContext(x => x.ParentId, () => item.Id, item).ToList();});//第二层db.ThenMapper(treeRoot.SelectMany(it => it.Child), it =>{it.Child = db.Queryable<Tree>().SetContext(x => x.ParentId, () => it.Id, it).ToList();});//第三层db.ThenMapper(treeRoot.SelectMany(it => it.Child).SelectMany(it => it.Child), it =>{it.Child = db.Queryable<Tree>().SetContext(x => x.ParentId, () => it.Id, it).ToList();});List<Tree> list = db.Queryable<Tree>().ToTree(it => it.Child, it => it.ParentId, 0);
}#endregion
----------------------------------------------------------------------------by202407150153-------
树递归查询
//设置关联字段
[SugarColumn(IsTreeKey = true)]
public string? Code { get; set; }
[SugarColumn(IsTreeKey = true)]
public string? ParentCode { get; set; } //父级字段
#region 树递归查询{//if (db.DbMaintenance.IsAnyTable("Tree", false))//{// db.DbMaintenance.DropTable<Tree>();//}//db.CodeFirst.InitTables<Tree>();//Tree tree = new Tree()//{// Id = 1,// Name = "一级树",// ParentId = 0,// Child = new List<Tree>// {// new Tree()// {// ParentId=1,// Id = 5,// Name="二级目录-1",// Child=new List<Tree>// {// new Tree() {// Id = 6,// Name="三级目录-1",// ParentId=2,// Child=new List<Tree>// {// new Tree() {// Id = 7,// ParentId=6,// Name="四级目录-1"// }// }// }// }// }// }//};//db.InsertNav<Tree>(tree)// .Include(it => it.Child)// .ThenInclude(c => c.Child)// .ThenInclude(c1 => c1.Child)// .ThenInclude(c2 => c2.Child)// .ExecuteCommand();查询所有下级从ParentId 为0 开始查询下级//List<Tree> childlist = db.Queryable<Tree>().ToTree(it => it.Child, it => it.ParentId, 0);查询所有上级//List<Tree> parentlist = db.Queryable<Tree>().ToParentList(it => it.ParentId, 6);条件查询,树形查询//List<Tree> treelist = db.Queryable<Tree>().Where(it => it.ParentId > 5)// .ToTree(it => it.Child, it => it.ParentId, 0);//if (db.DbMaintenance.IsAnyTable("Tree2", false))//{// db.DbMaintenance.DropTable<Tree2>();//}//db.CodeFirst.InitTables<Tree2>();//List<Tree2> tree2addlist = new List<Tree2>()//{ // new Tree2()// {// Name = "一级树",// ParentCode ="",// Code="001"// },// new Tree2()// {// ParentCode="001", // Name="二级目录-1",// Code="002"// },// new Tree2() // {// Name="三级目录-1",// ParentCode="002",// Code="003"// },// new Tree2() // { // ParentCode="003",// Name="四级目录-1",// Code="004"// }//}; //db.Insertable<Tree2>(tree2addlist) // .ExecuteCommand();//List<Tree2> child21list = db.Queryable<Tree2>().ToTree(it => it.Child, it => it.ParentCode, "001");//List<Tree2> child22list = db.Queryable<Tree2>().ToTree(it => it.Child, it => it.ParentCode, "002");查询所有上级//List<Tree2> parent2list = db.Queryable<Tree2>().ToParentList(it => it.Child, "004");条件查询,树形查询//List<Tree2> tree2list = db.Queryable<Tree2>().Where(it => it.Name.Contains("目录"))// .ToTree(it => it.Child, it => it.ParentCode, "001");}#endregion
3.16、动态表达式
数据结构,可以又多个表达式组合成一个表达式,也可以把表达式拆解---->组建成sql语句;
动态表达式
拓展用例
Queryable.Or
表达式解析器解析表达式
Where条件解析
select解析
字段名称解析
#region 表达式目录树{//表达式目录树连写{Console.WriteLine("========================================================================");string CompanyName = "";int? id = 1;//用例1:连写 不等于空 后面Expression<Func<Company, bool>> exp = Expressionable.Create<Company>() //创建表达式.AndIF(string.IsNullOrWhiteSpace(CompanyName) == false, it => it.CompanyName == CompanyName).AndIF(id != null, it => it.Id == id).ToExpression();//注意 这一句 不能少 var list = db.Queryable<Company>().Where(exp).ToList();//直接用就行了不需要判段 null和加true}//表达式目录树分开写{Console.WriteLine("========================================================================");string CompanyName = "音娱乐行";int? id = 1;Expressionable<Company> expable = Expressionable.Create<Company>();if (string.IsNullOrWhiteSpace(CompanyName) == false){expable.And(it => it.CompanyName == CompanyName);}if (id != null){expable.And(it => it.CompanyName == CompanyName);}Expression<Func<Company, bool>> exp = expable.ToExpression();//要用变量 var exp=db.Queryable<Company>().Where(exp).ToList();//直接用就行了不需要判段 null和加true}//拓展用例{Console.WriteLine("========================================================================");var names = new string[] { "音娱乐行", "乐善其行" };Expressionable<Company> exp = Expressionable.Create<Company>();foreach (var item in names){exp.Or(it => it.CompanyName.Contains(item.ToString()));}var list = db.Queryable<Company>().Where(exp.ToExpression()).ToList();}// Queyable.Or{Console.WriteLine("========================================================================");var exp = Expressionable.Create<Company>().And(it => it.Id == 1).Or(it => it.Id == 100).ToExpression();//注意 这一句 不能少var list = db.Queryable<Company>().Where(exp).ToList();}//解析表达式目录树{Console.WriteLine("========================================================================");var expContext = new SqlServerExpressionContext();Expression<Func<Company, bool>> exp = c => c.CompanyName.Contains("朝夕教育");expContext.Resolve(exp, ResolveExpressType.WhereSingle);var wheresql = expContext.Result.GetString();var pars = expContext.Parameters;db.Queryable<Company>().Where(wheresql).AddParameters(pars).ToList();}//匿名表达式解析{Console.WriteLine("========================================================================");DbType dbtype = DbType.SqlServer;ExpressionContext expContext = null;switch (dbtype){case DbType.MySql:expContext = new MySqlExpressionContext();break;case DbType.SqlServer:expContext = new SqlServerExpressionContext();break;case DbType.Sqlite:expContext = new SqliteExpressionContext();break;case DbType.Oracle:expContext = new OracleExpressionContext();break;case DbType.PostgreSQL:expContext = new PostgreSQLExpressionContext();break;case DbType.Dm:expContext = new DmExpressionContext();break;case DbType.Kdbndp:expContext = new KdbndpExpressionContext();break;default:throw new Exception("不支持");}Expression<Func<Company, bool>> exp = c => c.CompanyName.Contains("朝夕教育");expContext.Resolve(exp, ResolveExpressType.WhereSingle);var wheresql = expContext.Result.GetString();var pars = expContext.Parameters;db.Queryable<Company>().Where(wheresql).AddParameters(pars).ToList();}#region Where条件解析{Console.WriteLine("========================================================================");var expContext = new SqlServerExpressionContext();Expression<Func<Company, bool>> exp = it => it.CompanyName.Contains("音娱乐行");expContext.Resolve(exp, ResolveExpressType.WhereSingle);var value = expContext.Result.GetString();var pars = expContext.Parameters;}#endregion#region Where-Like解析{Console.WriteLine("========================================================================");Expression<Func<Student, bool>> exp = it => it.Name.Contains("Richard老师");ExpressionContext expContext = new ExpressionContext();expContext.Resolve(exp, ResolveExpressType.WhereMultiple);var value = expContext.Result.GetString();var pars = expContext.Parameters;}#endregion#region Select的解析 {Console.WriteLine("========================================================================");Expression<Func<Company, CompanyDto>> exp = it => new CompanyDto(){CompanyName = it.CompanyName,CreateTime = it.CreateTime,};ExpressionContext expContext = new ExpressionContext();expContext.IsSingle = false;expContext.Resolve(exp, ResolveExpressType.SelectSingle);var selectorValue = expContext.Result.GetString();var pars = expContext.Parameters;}#endregion }#endregion
3.17、跨库查询
在开发中,避免不了会有多个数据库存储数据。
如果在分库后,涉及到业务数据的链接查询,A库,B库;
从业务上让A库和B库链接查询;
使用SqlServer同义词;
#region 跨库查询{List<ConnectionConfig> connetctionlist = new List<ConnectionConfig>(){new ConnectionConfig(){ConfigId="db1",DbType=DbType.SqlServer,ConnectionString=CustomConnectionConfig.ConnectionString001,IsAutoCloseConnection=true},new ConnectionConfig(){ConfigId="db2",DbType=DbType.SqlServer,ConnectionString=CustomConnectionConfig.ConnectionString003,IsAutoCloseConnection=true}};using (SqlSugarClient db = new SqlSugarClient(connetctionlist)){{db.Aop.OnLogExecuting = (s, p) =>{Console.WriteLine("----------------------------");Console.WriteLine($"Sql语句:{s}");};}db.GetConnection("db1").DbMaintenance.CreateDatabase();db.GetConnection("db2").DbMaintenance.CreateDatabase();if (db.GetConnection("db1").DbMaintenance.IsAnyTable("OrderHead", false)){db.GetConnection("db1").DbMaintenance.DropTable<OrderHead>();}if (db.GetConnection("db2").DbMaintenance.IsAnyTable("OrderItem", false)){db.GetConnection("db2").DbMaintenance.DropTable<OrderItem>();}db.GetConnection("db1").CodeFirst.InitTables<OrderHead>();db.GetConnection("db2").CodeFirst.InitTables<OrderItem>();List<OrderHead> orders = new List<OrderHead>(){new OrderHead(){Id= 1,Name="自行车订单",Price=3000,CreateTime=DateTime.Now,CountInfo=1,}};List<OrderItem> itemsList = new List<OrderItem>(){new OrderItem(){CreateTime=DateTime.Now,Price=2900,ItemId=1,OrderId=1,},new OrderItem(){CreateTime=DateTime.Now,Price=100,ItemId=2,OrderId=1,}};db.GetConnection("db1").Insertable(orders).ExecuteCommand();db.GetConnection("db2").Insertable(itemsList).ExecuteCommand();//通过实体类特性Tenant自动映射不同数据库进行查询{var list = db.QueryableWithAttr<OrderItem>().Includes(z => z.Order).ToList(); //1行代码就搞定了2个库联表查询var list1 = db.QueryableWithAttr<OrderHead>().Includes(z => z.Items).ToList(); //1行代码就搞定了2个库联表查询}//不通过特性实现跨库导航{var list = db.GetConnection("db2").Queryable<OrderItem>()//Orderitem是db2.CrossQuery(typeof(OrderHead), "db1")//Order是db1.Includes(z => z.Order).ToList();var list1 = db.GetConnection("db1").Queryable<OrderHead>()//Orderitem是db2.CrossQuery(typeof(OrderItem), "db2")//Order是db1.Includes(z => z.Items).ToList();}{var list = db.Queryable<OrderHead>().AS("ZhaoxiSqlSugarDb.dbo.OrderHead").ToList();//多表跨库var list1 = db.Queryable<OrderHead>().AS("ZhaoxiSqlSugarDb.dbo.OrderHead") // AS("").LeftJoin<OrderItem>((o, i) => o.Id == i.OrderId).AS<OrderItem>("ZhaoxiSqlSugarDb_Item.dbo.OrderItem") //AS<T> .ToList();}}}#endregion
3.18、报表查询
在开发中,对于一些报表数据,如果使用Sql语句去查询,很复杂,Sqlsugar轻松支持
统计当前年份数据
统计最近三年的数据
统计最近十年的数据
统计今年一月份数据
统计最近三年一月份数据
统计最近10年一月份数据
#region 初始化表结构和数据
{db.Aop.OnLogExecuting = (s, p) =>{Console.WriteLine("----------------------------");Console.WriteLine($"Sql语句:{s}");};if (db.DbMaintenance.IsAnyTable("Operateinfo", false)){db.DbMaintenance.DropTable<Operateinfo>();}db.CodeFirst.InitTables<Operateinfo>();List<Operateinfo> list = new List<Operateinfo>();for (int i = 0; i < 100000; i++){list.Add(new Operateinfo(){Operate_time = DateTime.Now.AddMonths(new Random().Next(-6, 6)).AddYears(new Random().Next(-20, 20)),Operate_Type = i,Userid = i,});}db.Fastest<Operateinfo>().BulkCopy(list);
}
#endregion//统计当前年份
{Console.WriteLine("统计当前年份");var queryableLeft = db.Reportable(ReportableDateType.MonthsInLast1years).ToQueryable<DateTime>();var queryableRight = db.Queryable<Operateinfo>();var resultlistx = db.Queryable(queryableLeft).ToList();var resultlist = db.Queryable(queryableLeft, queryableRight, JoinType.Left, (x1, x2) => x2.Operate_time.ToString("yyyy-MM") == x1.ColumnName.ToString("yyyy-MM")).GroupBy((x1, x2) => x1.ColumnName).Select((x1, x2) => new{count = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)), //null的数据要为0所以不能用countdate = x1.ColumnName.ToString("yyyy-MM")}).ToList().OrderBy(c => c.date).ToList();var queryableLeft1 = resultlist.Sum(c => c.count);int lastYearcoutn = db.Queryable<Operateinfo>().Count(c => c.Operate_time.Year == 2022);
}{//统计最近三年Console.WriteLine("统计最近三年");var queryableLeft = db.Reportable(ReportableDateType.MonthsInLast3years).ToQueryable<DateTime>();var queryableRight = db.Queryable<Operateinfo>();var resultlist = db.Queryable(queryableLeft, queryableRight, JoinType.Left, (x1, x2) => x2.Operate_time.ToString("yyyy-MM") == x1.ColumnName.ToString("yyyy-MM")).GroupBy((x1, x2) => x1.ColumnName).Select((x1, x2) => new{count = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)), //null的数据要为0所以不能用countdate = x1.ColumnName.ToString("yyyy-MM")}).ToList().OrderBy(c => c.date).ToList();var threeYearCount = resultlist.Sum(c => c.count);int threeYearCount1 = db.Queryable<Operateinfo>().Count(c => c.Operate_time.Year == 2022 || c.Operate_time.Year == 2021 || c.Operate_time.Year == 2020);}{//统计最近10年;Console.WriteLine("最近10年");var queryableLeft = db.Reportable(ReportableDateType.MonthsInLast10years).ToQueryable<DateTime>();var queryableRight = db.Queryable<Operateinfo>();var resultlist = db.Queryable(queryableLeft, queryableRight, JoinType.Left, (x1, x2) => x2.Operate_time.ToString("yyyy-MM") == x1.ColumnName.ToString("yyyy-MM")).GroupBy((x1, x2) => x1.ColumnName).Select((x1, x2) => new{count = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)), //null的数据要为0所以不能用countdate = x1.ColumnName.ToString("yyyy-MM")}).ToList().OrderBy(c => c.date).ToList();var tenYearCount = resultlist.Sum(c => c.count);int tenYearCount1 = db.Queryable<Operateinfo>().Count(c => c.Operate_time.Year == 2022|| c.Operate_time.Year == 2021|| c.Operate_time.Year == 2020|| c.Operate_time.Year == 2019|| c.Operate_time.Year == 2018|| c.Operate_time.Year == 2017|| c.Operate_time.Year == 2016|| c.Operate_time.Year == 2015|| c.Operate_time.Year == 2014|| c.Operate_time.Year == 2013);
}{//统计今年一月份统计 Console.WriteLine("统计今年一月份统计 ");var queryableLeft = db.Reportable(ReportableDateType.years1).ToQueryable<DateTime>();var queryableRight = db.Queryable<Operateinfo>();var resultlist = db.Queryable(queryableLeft, queryableRight, JoinType.Left, (x1, x2) => x2.Operate_time.ToString("yyyy-MM") == x1.ColumnName.ToString("yyyy-MM")).GroupBy((x1, x2) => x1.ColumnName).Select((x1, x2) => new{count = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)), //null的数据要为0所以不能用countdate = x1.ColumnName.ToString("yyyy-MM")}).ToList().OrderBy(c => c.date).ToList();var years1Count1 = resultlist.Sum(c => c.count);int years1Count2 = db.Queryable<Operateinfo>().Count(c => c.Operate_time.Year == 2022 && c.Operate_time.Month == 1);}{//最近三年一月份统计 Console.WriteLine("最近三年一月份统计 ");var queryableLeft = db.Reportable(ReportableDateType.years3).ToQueryable<DateTime>();var queryableRight = db.Queryable<Operateinfo>();var resultlist = db.Queryable(queryableLeft, queryableRight, JoinType.Left, (x1, x2) => x2.Operate_time.ToString("yyyy-MM") == x1.ColumnName.ToString("yyyy-MM")).GroupBy((x1, x2) => x1.ColumnName).Select((x1, x2) => new{count = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)), //null的数据要为0所以不能用countdate = x1.ColumnName.ToString("yyyy-MM")}).ToList().OrderBy(c => c.date).ToList();var years1Count = resultlist.Sum(c => c.count);int years1Count1 = db.Queryable<Operateinfo>().Count(c => (c.Operate_time.Year == 2022 && c.Operate_time.Month == 1) || (c.Operate_time.Year == 2021 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2020 && c.Operate_time.Month == 1));
}{//最近10年一月份统计 Console.WriteLine("最近10年一月份统计 ");var queryableLeft = db.Reportable(ReportableDateType.years10).ToQueryable<DateTime>();var queryableRight = db.Queryable<Operateinfo>();var resultlist = db.Queryable(queryableLeft, queryableRight, JoinType.Left, (x1, x2) => x2.Operate_time.ToString("yyyy-MM") == x1.ColumnName.ToString("yyyy-MM")).GroupBy((x1, x2) => x1.ColumnName).Select((x1, x2) => new{count = SqlFunc.AggregateSum(SqlFunc.IIF(x2.Id > 0, 1, 0)), //null的数据要为0所以不能用countdate = x1.ColumnName.ToString("yyyy-MM")}).ToList().OrderBy(c => c.date).ToList();var queryableLeft1 = resultlist.Sum(c => c.count);int years1Count = db.Queryable<Operateinfo>().Count(c =>(c.Operate_time.Year == 2022 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2021 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2020 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2019 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2018 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2017 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2016 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2015 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2014 && c.Operate_time.Month == 1)|| (c.Operate_time.Year == 2013 && c.Operate_time.Month == 1));
}
至此您已成为使用此orm的高级开发 202407160036
--无他唯手熟尔!
sqlsugar 官网-CSDN博客
国产精品ORM框架-SqlSugar详解 SqlSugar初识 专题二-CSDN博客
4、进阶功能
5、集成整合
6、脚手架应用