Admin.Net第五章:数据库操作与SqlSugar集成
目录#
1. SqlSugar简介与配置#
1.1 什么是SqlSugar#
SqlSugar是一款老牌的.NET开源ORM框架,具有以下特点:
- 高性能:性能接近原生ADO.NET
- 多数据库支持:支持MySQL、SQL Server、Oracle、PostgreSQL、SQLite、达梦等20+数据库
- 简单易用:链式语法,学习成本低
- 功能丰富:支持CodeFirst、DBFirst、读写分离、分表等
1.2 Admin.NET中的SqlSugar配置#
配置文件(appsettings.json):
{
"DbSettings": {
"EnableInitDb": true,
"EnableInitSeed": true,
"EnableDiffLog": false,
"EnableUnderLine": true,
"DbConfigs": [
{
"ConfigId": "1300000000001",
"DbType": "MySql",
"ConnectionString": "Data Source=localhost;Database=AdminNET;User ID=root;Password=123456;pooling=true;port=3306;sslmode=none;CharSet=utf8mb4;AllowLoadLocalInfile=true",
"IsAutoCloseConnection": true,
"EnableSqlLog": true,
"EnableDiffLog": false,
"SlaveConnectionConfigs": []
}
]
}
}
配置说明:
| 配置项 | 说明 |
|---|---|
| EnableInitDb | 是否自动创建数据库和表 |
| EnableInitSeed | 是否初始化种子数据 |
| EnableDiffLog | 是否启用差异日志 |
| EnableUnderLine | 是否将驼峰命名转换为下划线命名 |
| ConfigId | 数据库配置标识 |
| DbType | 数据库类型 |
| ConnectionString | 连接字符串 |
| IsAutoCloseConnection | 是否自动关闭连接 |
| EnableSqlLog | 是否启用SQL日志 |
1.3 SqlSugar服务注册#
// SqlSugar配置
public static class SqlSugarSetup
{
public static void AddSqlSugar(this IServiceCollection services)
{
var dbSettings = App.GetConfig<DbSettings>("DbSettings");
// 注册SqlSugar客户端
services.AddSingleton<ISqlSugarClient>(sp =>
{
var connectionConfigs = dbSettings.DbConfigs.Select(config => new ConnectionConfig
{
ConfigId = config.ConfigId,
DbType = (SqlSugar.DbType)Enum.Parse(typeof(SqlSugar.DbType), config.DbType),
ConnectionString = config.ConnectionString,
IsAutoCloseConnection = config.IsAutoCloseConnection,
MoreSettings = new ConnMoreSettings
{
IsAutoRemoveDataCache = true,
SqlServerCodeFirstNvarchar = true
},
ConfigureExternalServices = new ConfigureExternalServices
{
EntityNameService = (type, entity) =>
{
// 驼峰转下划线
if (dbSettings.EnableUnderLine)
entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName);
},
EntityService = (property, column) =>
{
// 驼峰转下划线
if (dbSettings.EnableUnderLine)
column.DbColumnName = UtilMethods.ToUnderLine(column.DbColumnName);
// 可空类型处理
if (column.IsPrimarykey == false && new NullabilityInfoContext()
.Create(property).WriteState is NullabilityState.Nullable)
{
column.IsNullable = true;
}
}
}
}).ToList();
var db = new SqlSugarScope(connectionConfigs, db =>
{
connectionConfigs.ForEach(config =>
{
var sqlSugarClient = db.GetConnectionScope((string)config.ConfigId);
// SQL执行日志
if (dbSettings.EnableSqlLog)
{
sqlSugarClient.Aop