UNIVPLMDataIntegration/Admin.NET/Admin.NET.Core/Utils/SqlSugarExtensions.cs

59 lines
1.7 KiB
C#
Raw Normal View History


namespace Admin.NET.Core.Utils;
public static class SqlSugarExtensions
{
private const string DefaultTenantId = "1300000000001";
2025-03-12 10:08:57 +08:00
public static ISqlSugarClient ForTenant<TEntity>(this ISqlSugarClient db)
{
var attr = typeof(TEntity).GetCustomAttribute<TenantAttribute>();
2025-03-12 10:08:57 +08:00
var tenantId = attr != null ? GetConfigIdFromAttribute(attr) : DefaultTenantId;
return db.AsTenant().GetConnection(tenantId ?? DefaultTenantId);
}
2025-03-12 10:08:57 +08:00
private static string GetConfigIdFromAttribute(TenantAttribute attr)
{
2025-03-12 10:08:57 +08:00
const string targetKey = "configId";
var type = attr.GetType();
2025-03-12 10:08:57 +08:00
// 方式1尝试通过属性获取
var prop = type.GetProperty(targetKey,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (prop != null)
{
return prop.GetValue(attr) as string;
}
2025-03-12 10:08:57 +08:00
// 方式2尝试通过私有字段获取
var fieldNames = new[]
{
2025-03-12 10:08:57 +08:00
$"<{targetKey}>k__BackingField", // 自动属性字段
$"_{targetKey}", // 常规私有字段 (如_configId)
$"m_{targetKey}", // 匈牙利命名法
"configId" // 直接字段访问
};
2025-03-12 10:08:57 +08:00
foreach (var name in fieldNames)
{
2025-03-12 10:08:57 +08:00
var field = type.GetField(name,
BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
return field.GetValue(attr) as string;
}
}
2025-03-12 10:08:57 +08:00
// 方式3通过Dynamic访问备用方案
try
{
dynamic d = attr;
return d.configId;
}
catch
{
return null;
}
}
}
2025-03-12 10:08:57 +08:00