2024-02-02 17:14:41 +08:00
|
|
|
|
namespace MesETL.App.Options;
|
2024-01-19 11:17:22 +08:00
|
|
|
|
|
2024-12-10 14:03:09 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// 多租户分库配置
|
|
|
|
|
/// </summary>
|
2024-01-19 11:17:22 +08:00
|
|
|
|
public class TenantDbOptions
|
|
|
|
|
{
|
2024-01-29 09:29:16 +08:00
|
|
|
|
public string? TenantKey { get; set; }
|
2024-02-02 17:14:41 +08:00
|
|
|
|
public string? UseDbGroup { get; set; }
|
2024-01-19 11:17:22 +08:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Key-Value: {DbName}-{TenantKeyLessThan}
|
|
|
|
|
/// </summary>
|
2024-02-02 17:14:41 +08:00
|
|
|
|
public Dictionary<string, int>? DbGroup { get; set; }
|
2024-01-19 11:17:22 +08:00
|
|
|
|
|
|
|
|
|
public string GetDbNameByTenantKeyValue(int tenantKeyValue)
|
|
|
|
|
{
|
|
|
|
|
// var dictionary = new SortedDictionary<int, string>();
|
|
|
|
|
// DbList.ForEach(pair => dictionary.Add(pair.Value, pair.Key));
|
|
|
|
|
// 注意配置顺序
|
2024-02-02 17:14:41 +08:00
|
|
|
|
if(DbGroup is null) throw new ApplicationException("分库配置中没有发现任何数据库");
|
2024-12-10 14:03:09 +08:00
|
|
|
|
|
|
|
|
|
#region 性能较低,不使用
|
|
|
|
|
|
|
|
|
|
// var dbName = DbGroup.Cast<KeyValuePair<string, int>?>()
|
|
|
|
|
// .FirstOrDefault(pair => pair?.Value != null && pair.Value.Value > tenantKeyValue)!.Value.Key;
|
|
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
|
|
string? dbName = null;
|
|
|
|
|
foreach (var (key, value) in DbGroup)
|
|
|
|
|
{
|
|
|
|
|
if (value > tenantKeyValue)
|
|
|
|
|
dbName = key;
|
|
|
|
|
}
|
|
|
|
|
|
2024-01-19 11:17:22 +08:00
|
|
|
|
return dbName ??
|
|
|
|
|
throw new ArgumentOutOfRangeException(nameof(tenantKeyValue),
|
2024-01-29 09:29:16 +08:00
|
|
|
|
$"分库配置中没有任何符合'{nameof(tenantKeyValue)}'值的数据库");
|
2024-01-19 11:17:22 +08:00
|
|
|
|
}
|
|
|
|
|
}
|