110 lines
3.0 KiB
C#
110 lines
3.0 KiB
C#
using Dapper;
|
|
using Microsoft.Extensions.Logging;
|
|
using YLErp;
|
|
using YLErp.Abstract;
|
|
using YLErp.DataBase.Interceptors;
|
|
|
|
namespace BaseOUDAL
|
|
{
|
|
public abstract class DBContextBase : DbContext, IOptUserBase
|
|
{
|
|
private LogLevel _logLevel;
|
|
|
|
public OptUserInfo OptUser { get; set; }
|
|
|
|
public DbSet<SysUpdateLog> SysUpdateLogs { get; set; }
|
|
|
|
protected DBContextBase()
|
|
{
|
|
//_logLevel = LogLevel.Debug;
|
|
}
|
|
|
|
[System.Diagnostics.Conditional("DEBUG")]
|
|
public void SetDebugLog()
|
|
{
|
|
_logLevel = LogLevel.Debug;
|
|
}
|
|
|
|
protected abstract string GetConnectionString();
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
{
|
|
var connectionString = GetConnectionString();
|
|
|
|
optionsBuilder.LogTo(log =>
|
|
{
|
|
if (_logLevel == LogLevel.Debug)
|
|
{
|
|
System.Diagnostics.Debug.WriteLine(log);
|
|
}
|
|
});
|
|
|
|
if (_logLevel == LogLevel.Debug)
|
|
{
|
|
optionsBuilder.AddInterceptors(DgDbCommandInterceptor.Default);
|
|
}
|
|
|
|
if (_ServerVersion == null)
|
|
{
|
|
_ServerVersion = ServerVersion.AutoDetect(connectionString);
|
|
}
|
|
|
|
//optionsBuilder.UseMySql(connectionString, _ServerVersion, options =>
|
|
//{
|
|
// options.CommandTimeout(300);
|
|
//});
|
|
|
|
optionsBuilder.UseMySql(connectionString, _ServerVersion);
|
|
}
|
|
|
|
public override int SaveChanges()
|
|
{
|
|
var tracer = new DataChangeTracer(this).AddTraces(OptUser);
|
|
|
|
var changes = base.SaveChanges();
|
|
|
|
tracer.SaveTracesAsync();
|
|
|
|
return changes;
|
|
}
|
|
|
|
public int SaveChanges(CancellationToken cancellationToken)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
return SaveChanges();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取实体数据库表名
|
|
/// </summary>
|
|
public string GetTableName<TEntity>() where TEntity : class
|
|
{
|
|
var entityType = Model.FindEntityType(typeof(TEntity));
|
|
return entityType.GetTableName();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 使用dapper方式执行简单的表删除
|
|
/// </summary>
|
|
public int BulkDelete<TEntity>(string where, object param = null) where TEntity : class
|
|
{
|
|
var tableName = GetTableName<TEntity>();
|
|
|
|
return Database.GetDbConnection().Execute($"delete from {tableName} where {where}", param);
|
|
}
|
|
|
|
public DataTraceDbContext GetDataTraceDbContext()
|
|
{
|
|
return new DataTraceDbContext(optionsBuilder =>
|
|
{
|
|
optionsBuilder.UseMySql(GetConnectionString(), _ServerVersion, options =>
|
|
{
|
|
options.CommandTimeout(300);
|
|
});
|
|
});
|
|
}
|
|
|
|
private static ServerVersion _ServerVersion;
|
|
}
|
|
} |