48 lines
1.5 KiB
C#
48 lines
1.5 KiB
C#
using SqlSugar;
|
||
using Microsoft.Extensions.Configuration;
|
||
|
||
namespace AssetManager.Data;
|
||
|
||
public static class SqlSugarConfig
|
||
{
|
||
private static IConfiguration? _configuration;
|
||
|
||
/// <summary>
|
||
/// 初始化配置(在Program.cs中调用)
|
||
/// </summary>
|
||
public static void Initialize(IConfiguration configuration)
|
||
{
|
||
_configuration = configuration;
|
||
}
|
||
|
||
public static ISqlSugarClient GetSqlSugarClient()
|
||
{
|
||
if (_configuration == null)
|
||
{
|
||
throw new InvalidOperationException("SqlSugarConfig has not been initialized. Call Initialize() first.");
|
||
}
|
||
|
||
// 从配置读取连接字符串,支持环境变量和appsettings.json
|
||
var connectionString = _configuration.GetConnectionString("Default")
|
||
?? throw new InvalidOperationException("Connection string 'Default' not found in configuration.");
|
||
|
||
return new SqlSugarScope(new ConnectionConfig()
|
||
{
|
||
ConnectionString = connectionString,
|
||
DbType = DbType.MySql,
|
||
IsAutoCloseConnection = true,
|
||
InitKeyType = InitKeyType.Attribute,
|
||
ConfigureExternalServices = new ConfigureExternalServices
|
||
{
|
||
EntityService = (property, column) =>
|
||
{
|
||
if (property.PropertyType == typeof(DateTime))
|
||
{
|
||
column.DataType = "datetime(3)";
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|