refactor: 重构优化db模块抽象

This commit is contained in:
陈淳
2024-01-22 18:30:01 +08:00
parent 88eba44f68
commit f43f1e7be1
15 changed files with 258 additions and 187 deletions

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
namespace Yi.Framework.SqlSugarCore.Abstractions
{
public interface ISqlSugarDbConnectionCreator
{
DbConnOptions Options { get; }
Action<ISqlSugarClient> OnSqlSugarClientConfig { get; set; }
Action<object, DataAfterModel> DataExecuted { get; set; }
Action<object, DataFilterModel> DataExecuting { get; set; }
Action<string, SugarParameter[]> OnLogExecuting { get; set; }
Action<string, SugarParameter[]> OnLogExecuted { get; set; }
Action<PropertyInfo, EntityColumnInfo> EntityService { get; set; }
ConnectionConfig Build(Action<ConnectionConfig>? action = null);
void SetDbAop(ISqlSugarClient currentDb);
}
}

View File

@@ -0,0 +1,110 @@
using System.Reflection;
using Microsoft.Extensions.Options;
using SqlSugar;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.SqlSugarCore
{
public class SqlSugarDbConnectionCreator: ISqlSugarDbConnectionCreator,ITransientDependency
{
public SqlSugarDbConnectionCreator(IOptions<DbConnOptions> options)
{
Options = options.Value;
}
public DbConnOptions Options { get; }
public void SetDbAop(ISqlSugarClient currentDb)
{
currentDb.Aop.OnLogExecuting = this.OnLogExecuting;
currentDb.Aop.OnLogExecuted = this.OnLogExecuted;
currentDb.Aop.DataExecuting = this.DataExecuting;
currentDb.Aop.DataExecuted = this.DataExecuted;
}
public ConnectionConfig Build(Action<ConnectionConfig>? action=null)
{
var dbConnOptions = Options;
#region options
if (dbConnOptions.DbType is null)
{
throw new ArgumentException("DbType配置为空");
}
var slavaConFig = new List<SlaveConnectionConfig>();
if (dbConnOptions.EnabledReadWrite)
{
if (dbConnOptions.ReadUrl is null)
{
throw new ArgumentException("读写分离为空");
}
var readCon = dbConnOptions.ReadUrl;
readCon.ForEach(s =>
{
//如果是动态saas分库这里的连接串都不能写死需要动态添加这里只配置共享库的连接
slavaConFig.Add(new SlaveConnectionConfig() { ConnectionString = s });
});
}
#endregion
#region config
var connectionConfig = new ConnectionConfig()
{
ConfigId= ConnectionStrings.DefaultConnectionStringName,
DbType = dbConnOptions.DbType ?? DbType.Sqlite,
ConnectionString = dbConnOptions.Url,
IsAutoCloseConnection = true,
SlaveConnectionConfigs = slavaConFig,
//设置codefirst非空值判断
ConfigureExternalServices = new ConfigureExternalServices
{
EntityService = (c, p) =>
{
if (new NullabilityInfoContext()
.Create(c).WriteState is NullabilityState.Nullable)
{
p.IsNullable = true;
}
EntityService(c, p);
}
},
//这里多租户有个坑,无效的
AopEvents = new AopEvents
{
DataExecuted = DataExecuted,
DataExecuting = DataExecuting,
OnLogExecuted = OnLogExecuted,
OnLogExecuting = OnLogExecuting
}
};
if (action is not null)
{
action.Invoke(connectionConfig);
}
#endregion
return connectionConfig;
}
[DisablePropertyInjection]
public Action<ISqlSugarClient> OnSqlSugarClientConfig { get; set; }
[DisablePropertyInjection]
public Action<object, DataAfterModel> DataExecuted { get; set; }
[DisablePropertyInjection]
public Action<object, DataFilterModel> DataExecuting { get; set; }
[DisablePropertyInjection]
public Action<string, SugarParameter[]> OnLogExecuting { get; set; }
[DisablePropertyInjection]
public Action<string, SugarParameter[]> OnLogExecuted { get; set; }
[DisablePropertyInjection]
public Action<PropertyInfo, EntityColumnInfo> EntityService { get; set; }
}
}

View File

@@ -41,66 +41,20 @@ namespace Yi.Framework.SqlSugarCore
public void SetSqlSugarClient(ISqlSugarClient sqlSugarClient) public void SetSqlSugarClient(ISqlSugarClient sqlSugarClient)
{ {
SqlSugarClient=sqlSugarClient; SqlSugarClient = sqlSugarClient;
} }
public SqlSugarDbContext(IAbpLazyServiceProvider lazyServiceProvider) public SqlSugarDbContext(IAbpLazyServiceProvider lazyServiceProvider)
{ {
LazyServiceProvider = lazyServiceProvider; LazyServiceProvider = lazyServiceProvider;
var dbConnOptions = Options; var connectionCreator = LazyServiceProvider.LazyGetRequiredService<ISqlSugarDbConnectionCreator>();
#region options connectionCreator.OnSqlSugarClientConfig = OnSqlSugarClientConfig;
if (dbConnOptions.DbType is null) connectionCreator.EntityService = EntityService;
{ connectionCreator.DataExecuting = DataExecuting;
throw new ArgumentException("DbType配置为空"); connectionCreator.DataExecuted = DataExecuted;
} connectionCreator.OnLogExecuting = OnLogExecuting;
var slavaConFig = new List<SlaveConnectionConfig>(); connectionCreator.OnLogExecuted = OnLogExecuted;
if (dbConnOptions.EnabledReadWrite) SqlSugarClient = new SqlSugarClient(connectionCreator.Build());
{ connectionCreator.SetDbAop(SqlSugarClient);
if (dbConnOptions.ReadUrl is null)
{
throw new ArgumentException("读写分离为空");
}
var readCon = dbConnOptions.ReadUrl;
readCon.ForEach(s =>
{
//如果是动态saas分库这里的连接串都不能写死需要动态添加这里只配置共享库的连接
slavaConFig.Add(new SlaveConnectionConfig() { ConnectionString = s });
});
}
#endregion
SqlSugarClient = new SqlSugarClient(new ConnectionConfig()
{
//准备添加分表分库
DbType = dbConnOptions.DbType ?? DbType.Sqlite,
ConnectionString = dbConnOptions.Url,
IsAutoCloseConnection = true,
SlaveConnectionConfigs = slavaConFig,
//设置codefirst非空值判断
ConfigureExternalServices = new ConfigureExternalServices
{
EntityService = (c, p) =>
{
if (new NullabilityInfoContext()
.Create(c).WriteState is NullabilityState.Nullable)
{
p.IsNullable = true;
}
EntityService(c,p);
}
}
},
db =>
{
db.Aop.DataExecuting = DataExecuting;
db.Aop.DataExecuted = DataExecuted;
db.Aop.OnLogExecuting = OnLogExecuting;
db.Aop.OnLogExecuted = OnLogExecuted;
//扩展
OnSqlSugarClientConfig(db);
});
} }
/// <summary> /// <summary>
@@ -248,14 +202,14 @@ namespace Yi.Framework.SqlSugarCore
/// <param name="property"></param> /// <param name="property"></param>
/// <param name="column"></param> /// <param name="column"></param>
protected virtual void EntityService(PropertyInfo property, EntityColumnInfo column) protected virtual void EntityService(PropertyInfo property, EntityColumnInfo column)
{ {
} }
public void BackupDataBase() public void BackupDataBase()
{ {
string directoryName = "database_backup"; string directoryName = "database_backup";
string fileName = DateTime.Now.ToString($"yyyyMMdd_HHmmss")+ $"_{SqlSugarClient.Ado.Connection.Database}"; string fileName = DateTime.Now.ToString($"yyyyMMdd_HHmmss") + $"_{SqlSugarClient.Ado.Connection.Database}";
if (!Directory.Exists(directoryName)) if (!Directory.Exists(directoryName))
{ {
Directory.CreateDirectory(directoryName); Directory.CreateDirectory(directoryName);
@@ -264,7 +218,7 @@ namespace Yi.Framework.SqlSugarCore
{ {
case DbType.MySql: case DbType.MySql:
//MySql //MySql
SqlSugarClient.DbMaintenance.BackupDataBase(SqlSugarClient.Ado.Connection.Database, $"{Path.Combine(directoryName, fileName) }.sql");//mysql 只支持.net core SqlSugarClient.DbMaintenance.BackupDataBase(SqlSugarClient.Ado.Connection.Database, $"{Path.Combine(directoryName, fileName)}.sql");//mysql 只支持.net core
break; break;

View File

@@ -16,6 +16,12 @@ namespace Yi.Framework.SqlSugarCore
service.Replace(new ServiceDescriptor(typeof(ISqlSugarDbContext), typeof(DbContext), ServiceLifetime.Scoped)); service.Replace(new ServiceDescriptor(typeof(ISqlSugarDbContext), typeof(DbContext), ServiceLifetime.Scoped));
return service; return service;
} }
public static IServiceCollection TryAddYiDbContext<DbContext>(this IServiceCollection service) where DbContext : class, ISqlSugarDbContext
{
service.TryAdd(new ServiceDescriptor(typeof(ISqlSugarDbContext), typeof(DbContext), ServiceLifetime.Scoped));
return service;
}
public static IServiceCollection AddYiDbContext<DbContext>(this IServiceCollection service,Action<DbConnOptions> options) where DbContext : class, ISqlSugarDbContext public static IServiceCollection AddYiDbContext<DbContext>(this IServiceCollection service,Action<DbConnOptions> options) where DbContext : class, ISqlSugarDbContext
{ {

View File

@@ -18,6 +18,7 @@ namespace Yi.Framework.SqlSugarCore.Uow
{ {
public class UnitOfWorkSqlsugarDbContextProvider<TDbContext> : ISugarDbContextProvider<TDbContext> where TDbContext : ISqlSugarDbContext public class UnitOfWorkSqlsugarDbContextProvider<TDbContext> : ISugarDbContextProvider<TDbContext> where TDbContext : ISqlSugarDbContext
{ {
private readonly ISqlSugarDbConnectionCreator _dbConnectionCreator;
private readonly string MasterTenantDbDefaultName = DbConnOptions.MasterTenantDbDefaultName; private readonly string MasterTenantDbDefaultName = DbConnOptions.MasterTenantDbDefaultName;
public ILogger<UnitOfWorkSqlsugarDbContextProvider<TDbContext>> Logger { get; set; } public ILogger<UnitOfWorkSqlsugarDbContextProvider<TDbContext>> Logger { get; set; }
@@ -30,7 +31,8 @@ namespace Yi.Framework.SqlSugarCore.Uow
IUnitOfWorkManager unitOfWorkManager, IUnitOfWorkManager unitOfWorkManager,
IConnectionStringResolver connectionStringResolver, IConnectionStringResolver connectionStringResolver,
ICancellationTokenProvider cancellationTokenProvider, ICancellationTokenProvider cancellationTokenProvider,
ICurrentTenant currentTenant ICurrentTenant currentTenant,
ISqlSugarDbConnectionCreator dbConnectionCreator
) )
{ {
UnitOfWorkManager = unitOfWorkManager; UnitOfWorkManager = unitOfWorkManager;
@@ -38,6 +40,7 @@ namespace Yi.Framework.SqlSugarCore.Uow
CancellationTokenProvider = cancellationTokenProvider; CancellationTokenProvider = cancellationTokenProvider;
CurrentTenant = currentTenant; CurrentTenant = currentTenant;
Logger = NullLogger<UnitOfWorkSqlsugarDbContextProvider<TDbContext>>.Instance; Logger = NullLogger<UnitOfWorkSqlsugarDbContextProvider<TDbContext>>.Instance;
_dbConnectionCreator = dbConnectionCreator;
} }
public virtual async Task<TDbContext> GetDbContextAsync() public virtual async Task<TDbContext> GetDbContextAsync()
@@ -72,7 +75,7 @@ namespace Yi.Framework.SqlSugarCore.Uow
protected virtual async Task<TDbContext> CreateDbContextAsync(IUnitOfWork unitOfWork, string connectionStringName, string connectionString) protected virtual async Task<TDbContext> CreateDbContextAsync(IUnitOfWork unitOfWork, string connectionStringName, string connectionString)
{ {
var dbContext = await CreateDbContextAsync(unitOfWork); var dbContext = await CreateDbContextAsync(unitOfWork);
//没有检测到使用多租户功能,默认使用默认库即可 //没有检测到使用多租户功能,默认使用默认库即可
@@ -98,25 +101,36 @@ namespace Yi.Framework.SqlSugarCore.Uow
{ {
//直接切换 //直接切换
configId = MasterTenantDbDefaultName; configId = MasterTenantDbDefaultName;
var conStrOrNull= dbOption.GetDefaultMasterSaasMultiTenancy(); var conStrOrNull = dbOption.GetDefaultMasterSaasMultiTenancy();
Volo.Abp.Check.NotNull(conStrOrNull,"租户主库未找到"); Volo.Abp.Check.NotNull(conStrOrNull, "租户主库未找到");
connectionString = conStrOrNull.Url; connectionString = conStrOrNull.Url;
} }
//租户Db的动态切换 //租户Db的动态切换
//二级缓存 //二级缓存
var changed = false;
if (!db.IsAnyConnection(configId)) if (!db.IsAnyConnection(configId))
{ {
//添加一个db到当前上下文 (Add部分不线上下文不会共享) var config = _dbConnectionCreator.Build(options =>
db.AddConnection(new ConnectionConfig()
{ {
DbType = dbOption.DbType!.Value, options.DbType = dbOption.DbType!.Value;
ConfigId = configId,//设置库的唯一标识 options.ConfigId = configId;//设置库的唯一标识
IsAutoCloseConnection = true, options.IsAutoCloseConnection = true;
ConnectionString = connectionString options.ConnectionString = connectionString;
}); });
//添加一个db到当前上下文 (Add部分不线上下文不会共享)
db.AddConnection(config);
changed = true;
} }
var currentDb = db.GetConnection(configId) as ISqlSugarClient; var currentDb = db.GetConnection(configId) as ISqlSugarClient;
//设置Aop
if (changed)
{
_dbConnectionCreator.SetDbAop(currentDb);
}
dbContext.SetSqlSugarClient(currentDb); dbContext.SetSqlSugarClient(currentDb);
return dbContext; return dbContext;
} }

View File

@@ -13,7 +13,7 @@ namespace Yi.AuditLogging.SqlSugarCore
public override void ConfigureServices(ServiceConfigurationContext context) public override void ConfigureServices(ServiceConfigurationContext context)
{ {
context.Services.Replace(new ServiceDescriptor(typeof(IAuditLogRepository), typeof(SqlSugarCoreAuditLogRepository), lifetime: ServiceLifetime.Transient)); context.Services.Replace(new ServiceDescriptor(typeof(IAuditLogRepository), typeof(SqlSugarCoreAuditLogRepository), lifetime: ServiceLifetime.Transient));
context.Services.AddYiDbContext<YiAuditLoggingDbContext>(); context.Services.TryAddYiDbContext<YiAuditLoggingDbContext>();
} }
} }

View File

@@ -7,6 +7,7 @@ using Yi.Framework.Bbs.Application.Contracts.Dtos.BbsUser;
using Yi.Framework.Bbs.Domain.Entities; using Yi.Framework.Bbs.Domain.Entities;
using Yi.Framework.Bbs.Domain.Managers; using Yi.Framework.Bbs.Domain.Managers;
using Yi.Framework.Rbac.Application.Contracts.IServices; using Yi.Framework.Rbac.Application.Contracts.IServices;
using Yi.Framework.Rbac.Domain.Authorization;
using Yi.Framework.Rbac.Domain.Shared.Consts; using Yi.Framework.Rbac.Domain.Shared.Consts;
using Yi.Framework.Rbac.Domain.Shared.Model; using Yi.Framework.Rbac.Domain.Shared.Model;
@@ -29,13 +30,16 @@ namespace Yi.Framework.Bbs.Application.Services.Analyses
[HttpGet("analyse/bbs-user/random")] [HttpGet("analyse/bbs-user/random")]
public async Task<List<BbsUserGetListOutputDto>> GetRandomUserAsync([FromQuery] PagedResultRequestDto input) public async Task<List<BbsUserGetListOutputDto>> GetRandomUserAsync([FromQuery] PagedResultRequestDto input)
{ {
var randUserIds = await _bbsUserManager._userRepository._DbQueryable // using (DataFilter.DisablePermissionHandler())
//.Where(x => x.UserName != UserConst.Admin) {
var randUserIds = await _bbsUserManager._userRepository._DbQueryable
//.Where(x => x.UserName != UserConst.Admin)
.OrderBy(x => SqlFunc.GetRandom()) .OrderBy(x => SqlFunc.GetRandom())
.Select(x => x.Id). .Select(x => x.Id).
ToPageListAsync(input.SkipCount, input.MaxResultCount); ToPageListAsync(input.SkipCount, input.MaxResultCount);
var output = await _bbsUserManager.GetBbsUserInfoAsync(randUserIds); var output = await _bbsUserManager.GetBbsUserInfoAsync(randUserIds);
return output.Adapt<List<BbsUserGetListOutputDto>>(); return output.Adapt<List<BbsUserGetListOutputDto>>();
}
} }
/// <summary> /// <summary>
@@ -45,14 +49,17 @@ namespace Yi.Framework.Bbs.Application.Services.Analyses
[HttpGet("analyse/bbs-user/integral-top")] [HttpGet("analyse/bbs-user/integral-top")]
public async Task<List<BbsUserGetListOutputDto>> GetIntegralTopUserAsync([FromQuery] PagedResultRequestDto input) public async Task<List<BbsUserGetListOutputDto>> GetIntegralTopUserAsync([FromQuery] PagedResultRequestDto input)
{ {
var randUserIds = await _bbsUserManager._userRepository._DbQueryable // using (DataFilter.DisablePermissionHandler())
// .Where(user => user.UserName != UserConst.Admin) {
.LeftJoin<BbsUserExtraInfoEntity>((user, info) => user.Id==info.UserId) var randUserIds = await _bbsUserManager._userRepository._DbQueryable
.OrderByDescending((user, info)=>info.Money) // .Where(user => user.UserName != UserConst.Admin)
.LeftJoin<BbsUserExtraInfoEntity>((user, info) => user.Id == info.UserId)
.OrderByDescending((user, info) => info.Money)
.Select((user, info) => user.Id). .Select((user, info) => user.Id).
ToPageListAsync(input.SkipCount, input.MaxResultCount); ToPageListAsync(input.SkipCount, input.MaxResultCount);
var output = await _bbsUserManager.GetBbsUserInfoAsync(randUserIds); var output = await _bbsUserManager.GetBbsUserInfoAsync(randUserIds);
return output.OrderByDescending(x=>x.Money).ToList().Adapt<List<BbsUserGetListOutputDto>>(); return output.OrderByDescending(x => x.Money).ToList().Adapt<List<BbsUserGetListOutputDto>>();
}
} }
/// <summary> /// <summary>
@@ -62,22 +69,24 @@ namespace Yi.Framework.Bbs.Application.Services.Analyses
[HttpGet("analyse/bbs-user")] [HttpGet("analyse/bbs-user")]
public async Task<BbsUserAnalyseGetOutput> GetUserAnalyseAsync() public async Task<BbsUserAnalyseGetOutput> GetUserAnalyseAsync()
{ {
// using (DataFilter.DisablePermissionHandler())
var registerUser = await _bbsUserManager._userRepository._DbQueryable.CountAsync(); {
var registerUser = await _bbsUserManager._userRepository._DbQueryable.CountAsync();
DateTime now = DateTime.Now; DateTime now = DateTime.Now;
DateTime yesterday = now.AddDays(-1); DateTime yesterday = now.AddDays(-1);
DateTime startTime = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day, 0, 0, 0); DateTime startTime = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day, 0, 0, 0);
DateTime endTime = startTime.AddHours(24); DateTime endTime = startTime.AddHours(24);
var yesterdayNewUser = await _bbsUserManager._userRepository._DbQueryable var yesterdayNewUser = await _bbsUserManager._userRepository._DbQueryable
.Where(x => x.CreationTime >= startTime && x.CreationTime <= endTime).CountAsync(); .Where(x => x.CreationTime >= startTime && x.CreationTime <= endTime).CountAsync();
var userOnline = (await _onlineService.GetListAsync(new OnlineUserModel { })).TotalCount; var userOnline = (await _onlineService.GetListAsync(new OnlineUserModel { })).TotalCount;
var output = new BbsUserAnalyseGetOutput() { OnlineNumber = userOnline, RegisterNumber = registerUser, YesterdayNewUser = yesterdayNewUser }; var output = new BbsUserAnalyseGetOutput() { OnlineNumber = userOnline, RegisterNumber = registerUser, YesterdayNewUser = yesterdayNewUser };
return output; return output;
}
} }
} }

View File

@@ -5,8 +5,8 @@
public string UserName { get; set; } = string.Empty; public string UserName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
public string Uuid { get; set; } public string? Uuid { get; set; }
public string Code { get; set; } public string? Code { get; set; }
} }
} }

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Data;
namespace Yi.Framework.Rbac.Domain.Authorization
{
public static class DataPermissionExtensions
{
/// <summary>
/// 关闭数据权限
/// </summary>
/// <param name="dataFilter"></param>
/// <returns></returns>
public static IDisposable DisablePermissionHandler(this IDataFilter dataFilter)
{
return dataFilter.Disable<IDataPermission>();
}
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Yi.Framework.Rbac.Domain.Authorization
{
/// <summary>
/// 数据权限过滤接口
/// </summary>
public interface IDataPermission
{
}
}

View File

@@ -15,7 +15,7 @@ namespace Yi.Framework.Rbac.SqlSugarCore
{ {
public override void ConfigureServices(ServiceConfigurationContext context) public override void ConfigureServices(ServiceConfigurationContext context)
{ {
context.Services.AddYiDbContext<YiRbacDbContext>(); context.Services.TryAddYiDbContext<YiRbacDbContext>();
} }
} }
} }

View File

@@ -1,5 +1,6 @@
using SqlSugar; using SqlSugar;
using Volo.Abp.DependencyInjection; using Volo.Abp.DependencyInjection;
using Yi.Framework.Rbac.Domain.Authorization;
using Yi.Framework.Rbac.Domain.Entities; using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.Rbac.Domain.Extensions; using Yi.Framework.Rbac.Domain.Extensions;
using Yi.Framework.Rbac.Domain.Shared.Consts; using Yi.Framework.Rbac.Domain.Shared.Consts;
@@ -16,8 +17,11 @@ namespace Yi.Framework.Rbac.SqlSugarCore
protected override void CustomDataFilter(ISqlSugarClient sqlSugarClient) protected override void CustomDataFilter(ISqlSugarClient sqlSugarClient)
{ {
if (DataFilter.IsEnabled<IDataPermission>())
DataPermissionFilter(sqlSugarClient); {
DataPermissionFilter(sqlSugarClient);
}
base.CustomDataFilter(sqlSugarClient); base.CustomDataFilter(sqlSugarClient);
} }
@@ -42,7 +46,7 @@ namespace Yi.Framework.Rbac.SqlSugarCore
if (/*CurrentUser.GetDeptId() is null ||*/ roleInfo is null) if (/*CurrentUser.GetDeptId() is null ||*/ roleInfo is null)
{ {
expUser.Or(it => it.Id == CurrentUser.Id); expUser.Or(it => it.Id == CurrentUser.Id);
expRole.Or(it => roleInfo.Select(x=>x.Id).Contains(it.Id)); expRole.Or(it => roleInfo.Select(x => x.Id).Contains(it.Id));
} }
else else
{ {
@@ -68,7 +72,7 @@ namespace Yi.Framework.Rbac.SqlSugarCore
//SQl OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) ) //SQl OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )
var allChildDepts = sqlSugarClient.Queryable<DeptEntity>().ToChildList(it => it.ParentId, CurrentUser.GetDeptId()); var allChildDepts = sqlSugarClient.Queryable<DeptEntity>().ToChildList(it => it.ParentId, CurrentUser.GetDeptId());
expUser.Or(it => allChildDepts.Select(f => f.Id).ToList().Contains(it.DeptId??Guid.Empty)); expUser.Or(it => allChildDepts.Select(f => f.Id).ToList().Contains(it.DeptId ?? Guid.Empty));
} }
else if (DataScopeEnum.USER.Equals(dataScope))//仅本人数据 else if (DataScopeEnum.USER.Equals(dataScope))//仅本人数据
{ {
@@ -85,30 +89,5 @@ namespace Yi.Framework.Rbac.SqlSugarCore
sqlSugarClient.QueryFilter.AddTableFilter(expUser.ToExpression()); sqlSugarClient.QueryFilter.AddTableFilter(expUser.ToExpression());
sqlSugarClient.QueryFilter.AddTableFilter(expRole.ToExpression()); sqlSugarClient.QueryFilter.AddTableFilter(expRole.ToExpression());
} }
protected override void DataExecuted(object oldValue, DataAfterModel entityInfo)
{
base.DataExecuted(oldValue, entityInfo);
}
protected override void DataExecuting(object oldValue, DataFilterModel entityInfo)
{
base.DataExecuting(oldValue, entityInfo);
}
protected override void OnLogExecuting(string sql, SugarParameter[] pars)
{
base.OnLogExecuting(sql, pars);
}
protected override void OnLogExecuted(string sql, SugarParameter[] pars)
{
base.OnLogExecuted(sql, pars);
}
protected override void OnSqlSugarClientConfig(ISqlSugarClient sqlSugarClient)
{
base.OnSqlSugarClientConfig(sqlSugarClient);
}
} }
} }

View File

@@ -10,36 +10,5 @@ namespace Acme.BookStore.SqlSugarCore
public YiDbContext(IAbpLazyServiceProvider lazyServiceProvider) : base(lazyServiceProvider) public YiDbContext(IAbpLazyServiceProvider lazyServiceProvider) : base(lazyServiceProvider)
{ {
} }
protected override void CustomDataFilter(ISqlSugarClient sqlSugarClient)
{
base.CustomDataFilter(sqlSugarClient);
}
protected override void DataExecuted(object oldValue, DataAfterModel entityInfo)
{
base.DataExecuted(oldValue, entityInfo);
}
protected override void DataExecuting(object oldValue, DataFilterModel entityInfo)
{
base.DataExecuting(oldValue, entityInfo);
}
protected override void OnLogExecuting(string sql, SugarParameter[] pars)
{
base.OnLogExecuting(sql, pars);
}
protected override void OnLogExecuted(string sql, SugarParameter[] pars)
{
base.OnLogExecuted(sql, pars);
}
protected override void OnSqlSugarClientConfig(ISqlSugarClient sqlSugarClient)
{
base.OnSqlSugarClientConfig(sqlSugarClient);
}
} }
} }

View File

@@ -9,36 +9,5 @@ namespace Yi.Abp.SqlSugarCore
public YiDbContext(IAbpLazyServiceProvider lazyServiceProvider) : base(lazyServiceProvider) public YiDbContext(IAbpLazyServiceProvider lazyServiceProvider) : base(lazyServiceProvider)
{ {
} }
protected override void CustomDataFilter(ISqlSugarClient sqlSugarClient)
{
base.CustomDataFilter(sqlSugarClient);
}
protected override void DataExecuted(object oldValue, DataAfterModel entityInfo)
{
base.DataExecuted(oldValue, entityInfo);
}
protected override void DataExecuting(object oldValue, DataFilterModel entityInfo)
{
base.DataExecuting(oldValue, entityInfo);
}
protected override void OnLogExecuting(string sql, SugarParameter[] pars)
{
base.OnLogExecuting(sql, pars);
}
protected override void OnLogExecuted(string sql, SugarParameter[] pars)
{
base.OnLogExecuted(sql, pars);
}
protected override void OnSqlSugarClientConfig(ISqlSugarClient sqlSugarClient)
{
base.OnSqlSugarClientConfig(sqlSugarClient);
}
} }
} }

View File

@@ -11,7 +11,7 @@ Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext() .Enrich.FromLogContext()
.WriteTo.Async(c => c.File("logs/all/log-.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Debug)) .WriteTo.Async(c => c.File("logs/all/log-.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Debug))
.WriteTo.Async(c => c.File("logs/error/errorlog-.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Error)) .WriteTo.Async(c => c.File("logs/error/errorlog-.txt", rollingInterval: RollingInterval.Day, restrictedToMinimumLevel: LogEventLevel.Error))
.WriteTo.Async(c => c.Console(restrictedToMinimumLevel: LogEventLevel.Information)) .WriteTo.Async(c => c.Console())
.CreateLogger(); .CreateLogger();
try try