Files
WMSlite/WmsLite.Api/Infrastructure/SqlSugarSetup.cs
T
zhougfandCursor fa1b286463 Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 14:17:47 +08:00

101 lines
3.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using WmsLite.Api.Infrastructure.HttpLogging;
namespace WmsLite.Api.Infrastructure;
public static class SqlSugarSetup
{
public static IServiceCollection AddSqlSugarSetup(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = ConnectionStringConfiguration.ResolvePostgreSql(configuration);
services.AddScoped<ISqlSugarClient>(sp =>
{
var httpContextAccessor = sp.GetRequiredService<IHttpContextAccessor>();
var config = new ConnectionConfig
{
ConnectionString = connectionString,
DbType = DbType.PostgreSQL,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
ConfigureExternalServices = new ConfigureExternalServices
{
EntityService = (property, column) =>
{
if (property.PropertyType == typeof(Dictionary<string, object>)
|| property.PropertyType == typeof(Dictionary<string, string>))
{
column.IsJson = true;
SetJsonbColumnType(column);
}
}
},
AopEvents = new AopEvents
{
OnLogExecuting = (sql, parameters) =>
{
var executable = TryFormatExecutableSql(DbType.PostgreSQL, sql, parameters);
HttpSqlLogContext.Append(httpContextAccessor.HttpContext, executable);
}
}
};
return new SqlSugarClient(config);
});
return services;
}
/// <summary>
/// 生成可在客户端直接执行的 SQL(参数已代入);失败时退回原始 SQL + 参数列表。
/// </summary>
private static string TryFormatExecutableSql(DbType dbType, string sql, SugarParameter[]? parameters)
{
if (string.IsNullOrEmpty(sql))
{
return string.Empty;
}
try
{
return UtilMethods.GetSqlString(dbType, sql, parameters);
}
catch
{
var sb = new StringBuilder();
sb.Append(sql);
if (parameters is { Length: > 0 })
{
sb.AppendLine();
sb.Append("-- params:");
foreach (var p in parameters)
{
sb.Append(' ').Append(p.ParameterName).Append('=').Append(p.Value);
}
}
return sb.ToString();
}
}
private static void SetJsonbColumnType(EntityColumnInfo column)
{
// Different SqlSugar versions expose this property with different names.
const string jsonb = "jsonb";
var columnTypeProperty = column.GetType().GetProperty("ColumnDataType", BindingFlags.Public | BindingFlags.Instance)
?? column.GetType().GetProperty("DataType", BindingFlags.Public | BindingFlags.Instance);
if (columnTypeProperty?.CanWrite == true && columnTypeProperty.PropertyType == typeof(string))
{
columnTypeProperty.SetValue(column, jsonb);
}
}
}