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.

116 lines
4.2 KiB
C#

using DS.WMS.PrintApi.Model;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using NLog;
using SqlSugar;
using System;
using System.Collections.Generic;
namespace DS.WMS.PrintApi.Middleware
{
public class SaasDbService: ISaasDbService
{
private readonly IServiceProvider _serviceProvider;
private readonly SqlSugarScope db;
private readonly ISaasDbService saasService;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// 构造函数
/// </summary>
/// <param name="serviceProvider"></param>
public SaasDbService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = (SqlSugarScope)_serviceProvider.GetRequiredService<ISqlSugarClient>();
}
/// <summary>
/// 获取主库信息
/// </summary>
/// <returns></returns>
public ISqlSugarClient GetMasterDb()
{
return db.GetConnection("1288018625843826688");
}
/// <summary>
/// 主库根据Id获取业务库Scope
/// </summary>
/// <param name="configId"></param>
/// <returns></returns>
public SqlSugarScopeProvider GetBizDbScopeById(object configId)
{
//db.RemoveConnection(configId);
if (!db.IsAnyConnection(configId))
{
var connInfo = GetMasterDb().Queryable<SysTenantLink>().Filter(null,true).First(x => x.TenantId == Convert.ToInt64(configId));
//用非默认ConfigId进行测试
//添加业务库只在当前上下文有效原理SqlSugarScope模式入门文档去看
db.AddConnection(new ConnectionConfig()
{
ConfigId = configId,
ConnectionString = connInfo.Connection,
DbType = connInfo.DbType,
IsAutoCloseConnection = true
});
var dbProvider = db.GetConnectionScope(configId);
dbProvider.Ado.CommandTimeOut = 30;
dbProvider.Aop.OnLogExecuting = (sql, pars) =>
{
string sqlStr = sql;
foreach (var item in pars)
{
if (item.Value != null && item.Value != DBNull.Value)
{
string? strValue = string.Empty;
if (item.DbType == System.Data.DbType.String)
{
strValue = "'" + (string)item.Value + "'";
}
else if (item.DbType == System.Data.DbType.Boolean)
{
strValue = (bool)item.Value ? "1" : "0";
}
else
{
strValue = item.Value.ToString();
}
sqlStr = sqlStr.Replace(item.ParameterName, strValue);
}
}
2 months ago
Console.WriteLine("执行的SQL" + Environment.NewLine + sqlStr);
};
//数据处理事件
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
{
};
//SQL执行完
dbProvider.Aop.OnLogExecuted = (sql, pars) =>
{
//执行完了可以输出SQL执行时间 (OnLogExecutedDelegate)
1 month ago
//Console.Write("time:" + db.Ado.SqlExecutionTime.ToString());
};
dbProvider.Aop.OnDiffLogEvent = it =>
{
//排除日志库操作
if (Convert.ToInt64(configId) != 1288018625843826680)
{
}
};
}
return db.GetConnectionScope(configId);
}
public SqlSugarScopeProvider GetMasterDbScope()
{
return db.GetConnectionScope("1288018625843826688");
}
}
}