You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
3.4 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using Admin.Core.Common;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Admin.Core.Extensions
{
/// <summary>
/// SqlSugar 启动服务
/// </summary>
public static class SqlsugarSetup
{
public static void AddSqlsugarSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
// 默认添加主数据库连接
MainDb.CurrentDbConnId = Appsettings.app(new string[] { "MainDB" });
// 把多个连接对象注入服务这里必须采用Scope因为有事务操作
services.AddScoped<ISqlSugarClient>(o =>
{
// 连接字符串
var listConfig = new List<ConnectionConfig>();
// 从库
var listConfig_Slave = new List<SlaveConnectionConfig>();
BaseDBConfig.MutiConnectionString.slaveDbs.ForEach(s =>
{
listConfig_Slave.Add(new SlaveConnectionConfig()
{
HitRate = s.HitRate,
ConnectionString = s.Connection
});
});
BaseDBConfig.MutiConnectionString.allDbs.ForEach(m =>
{
listConfig.Add(new ConnectionConfig()
{
ConfigId = m.ConnId.ObjToString().ToLower(),
ConnectionString = m.Connection,
DbType = (DbType)m.DbType,
IsAutoCloseConnection = true,
// Check out more information: https://github.com/anjoy8/Admin.Core/issues/122
MoreSettings = new ConnMoreSettings()
{
//IsWithNoLockQuery = true,
IsAutoRemoveDataCache = true
},
// 从库
SlaveConnectionConfigs = listConfig_Slave,
// 自定义特性
ConfigureExternalServices = new ConfigureExternalServices()
{
EntityService = (property, column) =>
{
if (column.IsPrimarykey && property.PropertyType == typeof(int))
{
column.IsIdentity = true;
}
}
},
InitKeyType = InitKeyType.Attribute
}
);
});
return new SqlSugarClient(listConfig);
});
}
private static string GetWholeSql(SugarParameter[] paramArr, string sql)
{
foreach (var param in paramArr)
{
sql.Replace(param.ParameterName, param.Value.ObjToString());
}
return sql;
}
private static string GetParas(SugarParameter[] pars)
{
string key = "【SQL参数】";
foreach (var param in pars)
{
key += $"{param.ParameterName}:{param.Value}\n";
}
return key;
}
}
}