chore:目录重构

This commit is contained in:
陈淳
2023-04-15 17:35:22 +08:00
parent a612af4f68
commit fb27fb8aa4
238 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Yi.Framework.Infrastructure.Sqlsugar
{
public class DbConnOptions
{
/// <summary>
/// 连接字符串,必填
/// </summary>
public string? Url { get; set; }
/// <summary>
/// 数据库类型
/// </summary>
public DbType? DbType { get; set; }
/// <summary>
/// 开启种子数据
/// </summary>
public bool EnabledDbSeed { get; set; } = false;
/// <summary>
/// 开启读写分离
/// </summary>
public bool EnabledReadWrite { get; set; } = false;
/// <summary>
/// 开启codefirst
/// </summary>
public bool EnabledCodeFirst { get; set; } = false;
/// <summary>
/// 实体程序集
/// </summary>
public List<string>? EntityAssembly { get; set; }
/// <summary>
/// 读写分离
/// </summary>
public List<string>? ReadUrl { get; set; }
}
}

View File

@@ -0,0 +1,147 @@
using System.Linq.Expressions;
using Furion.DependencyInjection;
using SqlSugar;
using Yi.Framework.Infrastructure.Data.Entities;
using Yi.Framework.Infrastructure.Ddd.Dtos.Abstract;
using Yi.Framework.Infrastructure.Ddd.Repositories;
using Yi.Framework.Infrastructure.Enums;
using Yi.Framework.Infrastructure.Helper;
namespace Yi.Framework.Infrastructure.Sqlsugar.Repositories
{
public class SqlsugarRepository<T> : SimpleClient<T>, IRepository<T> ,ITransient where T : class, new()
{
public SqlsugarRepository(ISqlSugarClient context) : base(context)
{
}
/// <summary>
/// 注释一下严格意义这里应该protected但是我认为 简易程度 与 耦合程度 中是需要进行衡量的
/// </summary>
public ISugarQueryable<T> _DbQueryable => AsQueryable();
protected ISqlSugarClient _Db { get { return Context; } set { } }
public async Task<List<T>> GetPageListAsync(Expression<Func<T, bool>> whereExpression, IPagedAndSortedResultRequestDto page)
{
return await base.GetPageListAsync(whereExpression, new PageModel { PageIndex = page.PageNum, PageSize = page.PageSize });
}
public async Task<List<T>> GetPageListAsync(Expression<Func<T, bool>> whereExpression, IPagedAndSortedResultRequestDto page, Expression<Func<T, object>>? orderByExpression = null, OrderByEnum orderByType = OrderByEnum.Asc)
{
return await base.GetPageListAsync(whereExpression, new PageModel { PageIndex = page.PageNum, PageSize = page.PageSize }, orderByExpression, orderByType.EnumToEnum<OrderByType>());
}
public async Task<List<T>> GetPageListAsync(Expression<Func<T, bool>> whereExpression, IPagedAndSortedResultRequestDto page, string? orderBy, OrderByEnum orderByType = OrderByEnum.Asc)
{
return await _DbQueryable.Where(whereExpression).OrderByIF(orderBy is not null, orderBy + " " + orderByType.ToString().ToLower()).ToPageListAsync(page.PageNum, page.PageSize);
}
public async Task<List<T>> GetPageListAsync(Expression<Func<T, bool>> whereExpression, int pageNum, int pageSize)
{
return await base.GetPageListAsync(whereExpression, new PageModel { PageIndex = pageNum, PageSize = pageSize });
}
public async Task<List<T>> GetPageListAsync(Expression<Func<T, bool>> whereExpression, int pageNum, int pageSize, Expression<Func<T, object>>? orderByExpression = null, OrderByEnum orderByType = OrderByEnum.Asc)
{
return await base.GetPageListAsync(whereExpression, new PageModel { PageIndex = pageNum, PageSize = pageSize }, orderByExpression, orderByType.EnumToEnum<OrderByType>());
}
public async Task<List<T>> GetPageListAsync(Expression<Func<T, bool>> whereExpression, int pageNum, int pageSize, string? orderBy, OrderByEnum orderByType = OrderByEnum.Asc)
{
return await _DbQueryable.Where(whereExpression).OrderByIF(orderBy is not null, orderBy + " " + orderByType.ToString().ToLower()).ToPageListAsync(pageNum, pageSize);
}
public async Task<bool> UpdateIgnoreNullAsync(T updateObj)
{
return await _Db.Updateable(updateObj).IgnoreColumns(true).ExecuteCommandAsync() > 0;
}
public override async Task<bool> DeleteAsync(T deleteObj)
{
//逻辑删除
if (deleteObj is ISoftDelete)
{
//反射赋值
ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, deleteObj);
return await UpdateAsync(deleteObj);
}
else
{
return await base.DeleteAsync(deleteObj);
}
}
public override async Task<bool> DeleteAsync(List<T> deleteObjs)
{
if (typeof(ISoftDelete).IsAssignableFrom(typeof(T)))
{
//反射赋值
deleteObjs.ForEach(e => ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, e));
return await UpdateRangeAsync(deleteObjs);
}
else
{
return await base.DeleteAsync(deleteObjs);
}
}
public override async Task<bool> DeleteAsync(Expression<Func<T, bool>> whereExpression)
{
if (typeof(ISoftDelete).IsAssignableFrom(typeof(T)))
{
var entities = await GetListAsync(whereExpression);
//反射赋值
entities.ForEach(e => ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, e));
return await UpdateRangeAsync(entities);
}
else
{
return await base.DeleteAsync(whereExpression);
}
}
public override async Task<bool> DeleteByIdAsync(dynamic id)
{
if (typeof(ISoftDelete).IsAssignableFrom(typeof(T)))
{
var entity = await GetByIdAsync(id);
//反射赋值
ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, entity);
return await UpdateAsync(entity);
}
else
{
return await _Db.Deleteable<T>().In(id).ExecuteCommandAsync() > 0;
}
}
public override async Task<bool> DeleteByIdsAsync(dynamic[] ids)
{
if (typeof(ISoftDelete).IsAssignableFrom(typeof(T)))
{
var entities = await _DbQueryable.In(ids).ToListAsync();
if (entities.Count == 0)
{
return false;
}
//反射赋值
entities.ForEach(e => ReflexHelper.SetModelValue(nameof(ISoftDelete.IsDeleted), true, e));
return await UpdateRangeAsync(entities);
}
else
{
return await base.DeleteByIdsAsync(ids);
}
}
}
}

View File

@@ -0,0 +1,147 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Yi.Framework.Infrastructure.CurrentUsers;
namespace Yi.Framework.Infrastructure.Sqlsugar
{
public class SqlSugarDbContext
{
/// <summary>
/// SqlSugar 客户端
/// </summary>
public ISqlSugarClient SqlSugarClient { get; set; }
protected ICurrentUser _currentUser;
protected ILogger<SqlSugarDbContext> _logger;
protected IOptions<DbConnOptions> _options;
public SqlSugarDbContext(IOptions<DbConnOptions> options, ICurrentUser currentUser, ILogger<SqlSugarDbContext> logger)
{
_currentUser = currentUser;
_logger = logger;
_options = options;
var dbConnOptions = options.Value;
#region options
if (dbConnOptions.DbType is null)
{
throw new ArgumentException(SqlsugarConst.DbType配置为空);
}
var slavaConFig = new List<SlaveConnectionConfig>();
if (dbConnOptions.EnabledReadWrite)
{
if (dbConnOptions.ReadUrl is null)
{
throw new ArgumentException(SqlsugarConst.);
}
var readCon = dbConnOptions.ReadUrl;
readCon.ForEach(s =>
{
//如果是动态saas分库这里的连接串都不能写死需要动态添加这里只配置共享库的连接
slavaConFig.Add(new SlaveConnectionConfig() { ConnectionString = s });
});
}
#endregion
SqlSugarClient = new SqlSugarScope(new ConnectionConfig()
{
//准备添加分表分库
DbType = dbConnOptions.DbType ?? DbType.Sqlite,
ConnectionString = dbConnOptions.Url,
IsAutoCloseConnection = true,
MoreSettings = new ConnMoreSettings()
{
DisableNvarchar = true
},
SlaveConnectionConfigs = slavaConFig,
//设置codefirst非空值判断
ConfigureExternalServices = new ConfigureExternalServices
{
EntityService = (c, p) =>
{
//高版C#写法 支持string?和string
if (new NullabilityInfoContext()
.Create(c).WriteState is NullabilityState.Nullable)
{
p.IsNullable = true;
}
}
}
},
db =>
{
db.Aop.DataExecuting = (oldValue, entityInfo) =>
{
//switch (entityInfo.OperationType)
//{
// case DataFilterType.UpdateByObject:
// if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.LastModificationTime)))
// {
// entityInfo.SetValue(DateTime.Now);
// }
// if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.LastModifierId)))
// {
// if (_currentUser != null)
// {
// entityInfo.SetValue(_currentUser.Id);
// }
// }
// break;
// case DataFilterType.InsertByObject:
// if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.CreationTime)))
// {
// entityInfo.SetValue(DateTime.Now);
// }
// if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.CreatorId)))
// {
// if (_currentUser != null)
// {
// entityInfo.SetValue(_currentUser.Id);
// }
// }
// //插入时需要租户id,先预留
// if (entityInfo.PropertyName.Equals(nameof(IMultiTenant.TenantId)))
// {
// //if (this.CurrentTenant is not null)
// //{
// // entityInfo.SetValue(this.CurrentTenant.Id);
// //}
// }
// break;
//}
};
db.Aop.OnLogExecuting = (s, p) =>
{
StringBuilder sb = new StringBuilder();
//sb.Append("执行SQL:" + s.ToString());
//foreach (var i in p)
//{
// sb.Append($"\r\n参数:{i.ParameterName},参数值:{i.Value}");
//}
sb.Append($"\r\n 完整SQL{UtilMethods.GetSqlString(DbType.MySql, s, p)}");
logger?.LogDebug(sb.ToString());
};
//扩展
OnSqlSugarClientConfig(db);
});
}
//上下文对象扩展
protected virtual void OnSqlSugarClientConfig(ISqlSugarClient sqlSugarClient)
{
}
}
}

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.Infrastructure.Sqlsugar
{
public class SqlsugarConst
{
public const string = "开启读写分离后,读库连接不能为空";
public const string DbType配置为空 = "DbType配置为空必须选择一个数据库类型";
}
}

View File

@@ -0,0 +1,19 @@
using Microsoft.Extensions.DependencyInjection;
namespace Yi.Framework.Infrastructure.Sqlsugar
{
/// <summary>
/// 这一块,需要做成上下文对象,会进行重构
/// </summary>
public static class SqlsugarExtensions
{
//使用上下文对象
public static void AddDbSqlsugarContextServer(this IServiceCollection services)
{
services.AddSingleton(x => x.GetRequiredService<SqlSugarDbContext>().SqlSugarClient);
services.AddSingleton<SqlSugarDbContext>();
}
}
}

View File

@@ -0,0 +1,71 @@
using Furion;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using Yi.Framework.Infrastructure.Ddd.Repositories;
namespace Yi.Framework.Infrastructure.Sqlsugar.Uow
{
public class SqlsugarUnitOfWork : IUnitOfWork
{
// <summary>
/// SqlSugar 对象
/// </summary>
private readonly ISqlSugarClient _sqlSugarClient;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="sqlSugarClient"></param>
public SqlsugarUnitOfWork(ISqlSugarClient sqlSugarClient)
{
_sqlSugarClient = sqlSugarClient;
}
/// <summary>
/// 开启工作单元处理
/// </summary>
/// <param name="context"></param>
/// <param name="unitOfWork"></param>
/// <exception cref="NotImplementedException"></exception>
public void BeginTransaction(FilterContext context, UnitOfWorkAttribute unitOfWork)
{
_sqlSugarClient.AsTenant().BeginTran();
}
/// <summary>
/// 提交工作单元处理
/// </summary>
/// <param name="resultContext"></param>
/// <param name="unitOfWork"></param>
/// <exception cref="NotImplementedException"></exception>
public void CommitTransaction(FilterContext resultContext, UnitOfWorkAttribute unitOfWork)
{
_sqlSugarClient.AsTenant().CommitTran();
}
/// <summary>
/// 回滚工作单元处理
/// </summary>
/// <param name="resultContext"></param>
/// <param name="unitOfWork"></param>
/// <exception cref="NotImplementedException"></exception>
public void RollbackTransaction(FilterContext resultContext, UnitOfWorkAttribute unitOfWork)
{
_sqlSugarClient.AsTenant().RollbackTran();
}
/// <summary>
/// 执行完毕(无论成功失败)
/// </summary>
/// <param name="context"></param>
/// <param name="resultContext"></param>
/// <exception cref="NotImplementedException"></exception>
public void OnCompleted(FilterContext context, FilterContext resultContext)
{
_sqlSugarClient.Dispose();
}
}
}