Falcon.SugarApi/Falcon.SugarApi/DatabaseManager/DbContextBase.cs
2024-08-19 16:03:11 +08:00

60 lines
2.4 KiB
C#

using Falcon.SugarApi.DatabaseDefinitions.EntityServices;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Linq;
namespace Falcon.SugarApi.DatabaseManager
{
/// <summary>
/// 数据库上下文基类
/// </summary>
public abstract class DbContextBase:SqlSugarClient
{
/// <summary>
/// 保存数据库日志
/// </summary>
public ILogger? Logger { get; set; }
/// <summary>
/// 使用链接配置构造数据库链接
/// </summary>
/// <param name="config">数据库配置</param>
/// <param name="service">服务提供器</param>
public DbContextBase(ConnectionConfig config,IServiceProvider service) : base(config) {
this.Logger = service.GetService(typeof(ILogger<>).MakeGenericType(GetType())) as ILogger;
ConfigureExternalServices(this.CurrentConnectionConfig);
}
/// <summary>
/// 使用服务提供程序和配置集合初始化数据库上下文
/// </summary>
/// <param name="service">服务提供程序</param>
/// <param name="configs">数据库上下文配置集合</param>
public DbContextBase(IServiceProvider service,params ConnectionConfig[] configs) : base(configs.ToList()) {
this.Logger = service.GetService(typeof(ILogger<>).MakeGenericType(GetType())) as ILogger;
foreach(var c in configs) {
ConfigureExternalServices(this.GetConnection(c.ConfigId).CurrentConnectionConfig);
}
}
private static void ConfigureExternalServices(ConnectionConfig config) {
config.ConfigureExternalServices ??= new ConfigureExternalServices();
var ces = config.ConfigureExternalServices;
ces.EntityNameService = (t,e) => {
new TableNameTableService().SetupTable(t,e);
};
ces.EntityService = (p,c) => {
new SetupKeyColumnServices().SetupColumn(p,c);
new SetupLengthColumnServices().SetupColumn(p,c);
new SetupNullableColumnServices().SetupColumn(p,c);
new JsonTypeColumnServices().SetupColumn(p,c);
};
}
/// <summary>
/// 是否能连接到数据库
/// </summary>
public bool CanConnection => this.Ado.IsValidConnection();
}
}