using SqlSugar; using System.Data; using System.Linq.Expressions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using WIDESEA_Core.Helper; using Microsoft.Data.SqlClient; using System.Drawing.Printing; using WIDESEA_Core.Tenants; using WIDESEA_Core.Seed; using WIDESEA_Core.DB; using WIDESEA_Core.Const; using WIDESEA_Core.AOP; using OfficeOpenXml.FormulaParsing.ExpressionGraph; using WIDESEA_Core.Enums; using WIDESEA_Core.Utilities; using Microsoft.AspNetCore.Mvc.RazorPages; using NetTaste; using WIDESEA_Core.DB.Models; namespace WIDESEA_Core.BaseRepository { public class RepositoryBase : IRepository where TEntity : class, new() { private readonly IUnitOfWorkManage _unitOfWorkManage; private readonly SqlSugarClient _dbBase; private ISqlSugarClient _db { get { ISqlSugarClient db = _dbBase; //多租户 //var mta = typeof(TEntity).GetCustomAttribute(); //if (mta is { TenantType: TenantTypeEnum.Db }) //{ // //获取租户信息 租户信息可以提前缓存下来 // if (App.User is { TenantId: > 0 }) // { // dynamic tenant = db.Queryable(MainDb.TenantTableName, "x").Where(MainDb.TenantId, "=", App.User.TenantId).First(); // if (tenant != null) // { // var iTenant = db.AsTenant(); // if (!iTenant.IsAnyConnection(tenant.TenantId)) // { // string conStr = tenant.ConnectionString; // ConnectionConfig connectionConfig = new ConnectionConfig() // { // ConfigId = tenant.TenantId, // ConnectionString = conStr.DecryptDES(AppSecret.DB), // DbType = (SqlSugar.DbType)tenant.DbType, // IsAutoCloseConnection = true, // AopEvents = new AopEvents() // { // DataExecuting = SqlSugarAop.DataExecuting, // } // }; // iTenant.AddConnection(connectionConfig); // } // return iTenant.GetConnection(tenant.TenantId); // } // } //} return db; } } /// /// 创建数据库连接对象 /// public ISqlSugarClient Db => _db; public RepositoryBase(IUnitOfWorkManage unitOfWorkManage) { _unitOfWorkManage = unitOfWorkManage; _dbBase = unitOfWorkManage.GetDbClient(); } /// /// 通过主键查询数据 /// /// 主键 /// 查询结果 public virtual TEntity QureyDataById(object id) { return _db.Queryable().In(id).Single(); } /// /// 通过主键数组查询数据 /// /// 主键数组 /// 查询结果集合 public virtual List QureyDataByIds(object[] lstIds) { return _db.Queryable().In(lstIds).ToList(); } /// /// 通过主键集合查询数据 /// /// 主键集合 /// 查询结果集合 public virtual List QureyDataByIds(List lstIds) { return _db.Queryable().In(lstIds).ToList(); } /// /// 添加单条数据 /// /// /// 影响行数 public virtual int AddData(TEntity entity) { IInsertable insert = _db.Insertable(entity); return insert.ExecuteReturnIdentity(); } public virtual bool AddData(TEntity entity, Expression>> expression) where TChild : class, new() { return _db.InsertNav(entity).Include(expression).ExecuteCommand(); } /// /// 添加多条数据 /// /// /// 影响行数 public virtual int AddData(List listEntity) { IInsertable insert = _db.Insertable(listEntity); return insert.ExecuteCommand(); } /// /// 通过主键删除数据 /// /// 主键 /// 删除结果 public virtual bool DeleteDataById(object id) { return _db.Deleteable().In(id).ExecuteCommandHasChange(); } /// /// 通过主键数据删除多条数据 /// /// 主键数组 /// 删除结果 public virtual bool DeleteDataByIds(object[] ids) { return _db.Deleteable().In(ids).ExecuteCommandHasChange(); } /// /// 通过实体数据删除数据 /// /// 主键数组 /// 删除结果 public virtual bool DeleteData(TEntity entity) { return _db.Deleteable(entity).ExecuteCommandHasChange(); } /// /// 通过实体集合数据删除数据 /// /// 主键数组 /// 删除结果 public virtual bool DeleteData(List listEntity) { return _db.Deleteable(listEntity).ExecuteCommandHasChange(); } /// /// 更新单条数据 /// /// /// public virtual bool UpdateData(TEntity entity) { return _db.Updateable(entity).ExecuteCommandHasChange(); } /// /// 更新多条数据 /// /// /// public virtual bool UpdateData(List listEntity) { return _db.Updateable(listEntity).ExecuteCommandHasChange(); } /// /// 指定列更新数据 /// /// /// /// /// public virtual bool UpdateData(TEntity entity, List lstColumns, List? lstIgnoreColumns = null) { IUpdateable update = _db.Updateable(entity); if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0) { update = update.IgnoreColumns(lstIgnoreColumns.ToArray()); } if (lstColumns != null && lstColumns.Count > 0) { update = update.UpdateColumns(lstColumns.ToArray()); } return update.ExecuteCommandHasChange(); } /// /// 查询所有数据 /// /// public virtual List QueryData() { return _db.Queryable().ToList(); } /// /// 条件查询数据 /// /// /// public virtual List QueryData(string where) { return _db.Queryable().WhereIF(!string.IsNullOrEmpty(where), where).ToList(); } /// /// 条件查询数据 /// /// /// public virtual List QueryData(Expression> whereExpression) { return _db.Queryable().WhereIF(whereExpression != null, whereExpression).ToList(); } public virtual TEntity QueryFirst(Expression> whereExpression) { return _db.Queryable().WhereIF(whereExpression != null, whereExpression).First(); } public virtual TResult QueryFirst(Expression> whereExpression, Expression> expression) { return _db.Queryable().WhereIF(whereExpression != null, whereExpression).Select(expression).First(); } /// /// 条件查询数据并排序 /// /// /// /// public virtual List QueryData(Expression> whereExpression, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } return _db.Queryable().WhereIF(whereExpression != null, whereExpression).OrderBy(orderByModels).ToList(); } /// /// 条件查询数据并排序 /// /// /// /// public virtual List QueryData(string where, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } return _db.Queryable().WhereIF(!string.IsNullOrEmpty(where), where).OrderBy(orderByModels).ToList(); } /// /// 查询指定数据对象 /// /// /// /// public virtual List QueryData(Expression> expression) { return _db.Queryable().Select(expression).ToList(); } /// /// 条件查询指定数据对象 /// /// /// /// /// /// public virtual List QueryData(Expression> expression, Expression> whereExpression, string orderByFields = "") { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).WhereIF(whereExpression != null, whereExpression).Select(expression).ToList(); } /// /// 条件查询数据并排序 /// /// /// /// /// public virtual List QueryData(Expression> whereExpression, Expression> orderByExpression, bool isAsc = true) { return _db.Queryable().OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc).WhereIF(whereExpression != null, whereExpression).ToList(); } /// /// 条件查询数据并排序 /// /// /// /// public virtual List QueryData(string where, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).WhereIF(!string.IsNullOrEmpty(where), where).ToList(); } /// /// 原生Sql语句查询数据 /// /// /// /// public virtual List QueryDataBySql(string sql, SugarParameter[]? parameters = null) { return _db.Ado.SqlQuery(sql, parameters); } /// /// 原生Sql语句查询数据 /// /// /// /// public virtual List QueryDynamicDataBySql(string sql, SugarParameter[]? parameters = null) { return _db.Ado.SqlQuery(sql, parameters); } /// /// 原生Sql语句查询数据 /// /// /// /// public virtual List QueryObjectDataBySql(string sql, SugarParameter[]? parameters = null) { return _db.Ado.SqlQuery(sql, parameters); } /// /// 原生Sql语句执行操作 /// /// /// /// public virtual int ExecuteSqlCommand(string sql, params SqlParameter[] sqlParameters) { return _db.Ado.ExecuteCommand(sql, sqlParameters); } /// /// 原生Sql语句查询数据 /// /// /// /// public virtual DataTable QueryTable(string sql, SugarParameter[]? parameters = null) { return _db.Ado.GetDataTable(sql, parameters); } /// /// 条件查询数据指定数量的行 /// /// /// /// /// public virtual List QueryData(Expression> whereExpression, int top, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).WhereIF(whereExpression != null, whereExpression).Take(top).ToList(); } /// /// 条件查询指定数量的行 /// /// /// /// /// public virtual List QueryData(string where, int top, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).WhereIF(!string.IsNullOrEmpty(where), where).Take(top).ToList(); } /// /// 分页查询 /// /// /// /// /// /// public virtual List QueryData(Expression> whereExpression, int pageIndex, int pageSize, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression).ToPageList(pageIndex, pageSize); } /// /// 分页查询 /// /// /// /// /// /// public virtual List QueryData(string where, int pageIndex, int pageSize, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(!string.IsNullOrEmpty(where), where).ToPageList(pageIndex, pageSize); } /// /// 分页查询 /// /// /// /// /// /// public virtual PageGridData QueryPage(Expression> whereExpression, int pageIndex, int pageSize, string? orderByFields = null) { int totalCount = 0; var list = _db.Queryable() .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression) .ToPageList(pageIndex, pageSize, ref totalCount); return new PageGridData { Rows = list, Total = totalCount }; } /// /// 分页查询 /// /// /// /// /// /// public virtual PageGridData QueryPage(Expression> whereExpression, int pageIndex, int pageSize, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } int totalCount = 0; List list = _db.Queryable() .OrderBy(orderByModels) .WhereIF(whereExpression != null, whereExpression) .ToPageList(pageIndex, pageSize, ref totalCount); return new PageGridData(totalCount, list); } /// /// 分页查询 /// /// /// /// /// /// public virtual PageGridData QueryPage(string where, int pageIndex, int pageSize, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } int totalCount = 0; List list = _db.Queryable() .WhereIF(!string.IsNullOrEmpty(where), where).OrderBy(orderByModels).ToPageList(pageIndex, pageSize, ref totalCount); return new PageGridData(totalCount, list); } /// /// 两表联查 /// /// /// /// /// /// /// /// public virtual List QueryTabs( Expression> joinExpression, Expression> selectExpression, Expression> whereExpressionT1, Expression> whereExpression) { List list = _db.Queryable(joinExpression).WhereIF(whereExpressionT1 != null, whereExpressionT1) .Select(selectExpression) .WhereIF(whereExpression != null, whereExpression).ToList(); return list; } public virtual List QueryTabs( Expression> joinExpression, Expression> selectExpression, Expression> whereExpressionT1, Expression> whereExpressionT2, Expression> whereExpression) { List list = _db.Queryable().WhereIF(whereExpressionT1 != null, whereExpressionT1).InnerJoin(_db.Queryable().WhereIF(whereExpressionT2 != null, whereExpressionT2), joinExpression).Select(selectExpression) .WhereIF(whereExpression != null, whereExpression).ToList(); return list; } /// /// 两表联查-分页 /// /// /// /// /// /// /// /// /// /// public virtual PageGridData QueryTabsPage(Expression> joinExpression, Expression> selectExpression, Expression> whereExpression, int pageIndex, int pageSize, string? orderByFields = null) { int totalCount = 0; List list = _db.Queryable(joinExpression) .Select(selectExpression) .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression) .ToPageList(pageIndex, pageSize, ref totalCount); return new PageGridData(totalCount, list); } /// /// 两表联合查询-分页-分组 /// /// /// /// /// /// /// /// /// /// /// /// public virtual PageGridData QueryTabsPage(Expression> joinExpression, Expression> selectExpression, Expression> whereExpression, Expression> groupExpression, int pageIndex, int pageSize, string? orderByFields = null) { int totalCount = 0; List list = _db.Queryable(joinExpression).GroupBy(groupExpression) .Select(selectExpression) .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression) .ToPageList(pageIndex, pageSize, ref totalCount); return new PageGridData(totalCount, list); } public Task QureyDataByIdAsync(object id) { return _db.Queryable().In(id).SingleAsync(); } public Task> QureyDataByIdsAsync(object[] lstIds) { return _db.Queryable().In(lstIds).ToListAsync(); } public Task> QureyDataByIdsAsync(List lstIds) { return _db.Queryable().In(lstIds).ToListAsync(); } public Task AddDataAsync(TEntity entity) { IInsertable insert = _db.Insertable(entity); return insert.ExecuteReturnIdentityAsync(); } public Task AddDataAsync(List listEntity) { IInsertable insert = _db.Insertable(listEntity); return insert.ExecuteReturnIdentityAsync(); } public Task DeleteDataByIdAsync(object id) { return _db.Deleteable().In(id).ExecuteCommandHasChangeAsync(); } public Task DeleteDataByIdsAsync(object[] ids) { return _db.Deleteable().In(ids).ExecuteCommandHasChangeAsync(); } public Task DeleteDataAsync(TEntity entity) { return _db.Deleteable(entity).ExecuteCommandHasChangeAsync(); } public Task DeleteDataAsync(List listEntity) { return _db.Deleteable(listEntity).ExecuteCommandHasChangeAsync(); } public Task UpdateDataAsync(TEntity entity) { return _db.Updateable(entity).ExecuteCommandHasChangeAsync(); } public Task UpdateDataAsync(List listEntity) { return _db.Updateable(listEntity).ExecuteCommandHasChangeAsync(); } public Task UpdateDataAsync(TEntity entity, List lstColumns, List? lstIgnoreColumns = null) { IUpdateable update = _db.Updateable(entity); if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0) { update = update.IgnoreColumns(lstIgnoreColumns.ToArray()); } if (lstColumns != null && lstColumns.Count > 0) { update = update.UpdateColumns(lstColumns.ToArray()); } return update.ExecuteCommandHasChangeAsync(); } public Task> QueryDataAsync() { return _db.Queryable().ToListAsync(); } public Task> QueryDataAsync(string where) { return _db.Queryable().WhereIF(!string.IsNullOrEmpty(where), where).ToListAsync(); } public Task> QueryDataAsync(Expression> whereExpression) { return _db.Queryable().WhereIF(whereExpression != null, whereExpression).ToListAsync(); } public Task QueryFirstAsync(Expression> whereExpression) { return _db.Queryable().WhereIF(whereExpression != null, whereExpression).FirstAsync(); } public Task QueryFirstAsync(Expression> whereExpression, Expression> expression) { return _db.Queryable().WhereIF(whereExpression != null, whereExpression).Select(expression).FirstAsync(); } public TResult QueryFirst(Expression> whereExpression, Expression> expression, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } return _db.Queryable().WhereIF(whereExpression != null, whereExpression).OrderBy(orderByModels).Select(expression).First(); } public Task QueryFirstAsync(Expression> whereExpression, Expression> expression, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } return _db.Queryable().WhereIF(whereExpression != null, whereExpression).OrderBy(orderByModels).Select(expression).FirstAsync(); } public TEntity QueryFirst(Expression> whereExpression, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } return _db.Queryable().WhereIF(whereExpression != null, whereExpression).OrderBy(orderByModels).First(); } public Task QueryFirstAsync(Expression> whereExpression, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } return _db.Queryable().WhereIF(whereExpression != null, whereExpression).OrderBy(orderByModels).FirstAsync(); } public Task> QueryDataAsync(Expression> whereExpression, string orderByFields) { return _db.Queryable().WhereIF(whereExpression != null, whereExpression).OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).ToListAsync(); } public Task> QueryDataAsync(string where, Dictionary orderBy) { List orderByModels = new List(); foreach (var item in orderBy) { OrderByModel orderByModel = new OrderByModel() { FieldName = item.Key, OrderByType = item.Value }; orderByModels.Add(orderByModel); } return _db.Queryable().WhereIF(!string.IsNullOrEmpty(where), where).OrderBy(orderByModels).ToListAsync(); } public Task> QueryDataAsync(Expression> expression) { return _db.Queryable().Select(expression).ToListAsync(); } public Task> QueryDataAsync(Expression> expression, Expression> whereExpression, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).WhereIF(whereExpression != null, whereExpression).Select(expression).ToListAsync(); } public Task> QueryDataAsync(Expression> whereExpression, Expression> orderByExpression, bool isAsc = true) { return _db.Queryable().OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc).WhereIF(whereExpression != null, whereExpression).ToListAsync(); } public Task> QueryDataAsync(string where, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).WhereIF(!string.IsNullOrEmpty(where), where).ToListAsync(); } public Task> QueryDataBySqlAsync(string sql, SugarParameter[]? parameters = null) { return _db.Ado.SqlQueryAsync(sql, parameters); } public Task> QueryDynamicDataBySqlAsync(string sql, SugarParameter[]? parameters = null) { return _db.Ado.SqlQueryAsync(sql, parameters); } public Task> QueryObjectDataBySqlAsync(string sql, SugarParameter[]? parameters = null) { return _db.Ado.SqlQueryAsync(sql, parameters); } public Task ExecuteSqlCommandAsync(string sql, params SqlParameter[] sqlParameters) { return _db.Ado.ExecuteCommandAsync(sql, sqlParameters); } public Task QueryTableAsync(string sql, SugarParameter[]? parameters = null) { return _db.Ado.GetDataTableAsync(sql, parameters); } public Task> QueryDataAsync(Expression> whereExpression, int top, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).WhereIF(whereExpression != null, whereExpression).Take(top).ToListAsync(); } public Task> QueryDataAsync(string where, int top, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields).WhereIF(!string.IsNullOrEmpty(where), where).Take(top).ToListAsync(); } public Task> QueryDataAsync(Expression> whereExpression, int pageIndex, int pageSize, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression).ToPageListAsync(pageIndex, pageSize); } public Task> QueryDataAsync(string where, int pageIndex, int pageSize, string orderByFields) { return _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(!string.IsNullOrEmpty(where), where).ToPageListAsync(pageIndex, pageSize); } public Task> QueryTabsAsync(Expression> joinExpression, Expression> selectExpression, Expression> whereExpression) { return _db.Queryable(joinExpression) .Select(selectExpression) .WhereIF(whereExpression != null, whereExpression).ToListAsync(); } public bool DeleteAndMoveIntoHty(TEntity entity, OperateTypeEnum operateType) { Type type = entity.GetType(); Assembly assembly = type.Assembly; Type? htyType = assembly.GetType(type.FullName + "_Hty"); if (htyType != null) { object? obj = Activator.CreateInstance(htyType); PropertyInfo keyPro = typeof(TEntity).GetKeyProperty(); PropertyInfo? operateTypePro = htyType.GetProperty(nameof(IBaseHistoryEntity.OperateType)); PropertyInfo? sourceIdPro = htyType.GetProperty(nameof(IBaseHistoryEntity.SourceId)); if (obj != null && keyPro != null && operateTypePro != null && sourceIdPro != null) { operateTypePro.SetValue(obj, operateType.ToString()); sourceIdPro.SetValue(obj, keyPro.GetValue(entity)); List propertyInfos = htyType.GetProperties().Where(x => x.Name != operateTypePro.Name && x.Name != sourceIdPro.Name && x.Name != keyPro.Name).ToList(); for (int i = 0; i < propertyInfos.Count; i++) { PropertyInfo propertyInfo = propertyInfos[i]; PropertyInfo? property = type.GetProperty(propertyInfo.Name); if (property != null) { if (propertyInfo.Name == nameof(BaseEntity.Modifier)) { propertyInfo.SetValue(obj, App.User.UserId > 0 ? App.User.UserName : "System"); } else if (propertyInfo.Name == nameof(BaseEntity.ModifyDate)) { propertyInfo.SetValue(obj, DateTime.Now); } else { propertyInfo.SetValue(obj, property.GetValue(entity)); } } } if (obj != null) _db.InsertableByObject(obj).AS(type.Name + "_Hty").ExecuteCommand(); } } return DeleteData(entity); } //public bool DeleteAndMoveIntoHty(TEntity entity, OperateTypeEnum operateType) //{ // // 核心逻辑:用事务保证原子性,异常捕获避免流程中断,日志辅助排查 // bool isSuccess = false; // string entityTypeName = entity?.GetType().Name ?? "未知实体"; // try // { // // 前置校验:实体不能为空 // if (entity == null) // { // return false; // } // Type entityType = entity.GetType(); // Assembly assembly = entityType.Assembly; // string htyTypeName = $"{entityType.FullName}_Hty"; // Type? htyType = assembly.GetType(htyTypeName); // // 1. 检查历史表类型是否存在 // if (htyType == null) // { // return false; // } // // 2. 创建历史表实例(处理无参构造函数不存在的情况) // object? htyObj; // try // { // htyObj = Activator.CreateInstance(htyType); // } // catch (Exception ex) // { // // _logger.LogError(ex, "DeleteAndMoveIntoHty:创建历史表实例 {HtyTypeName} 失败", htyTypeName); // return false; // } // if (htyObj == null) // { // // _logger.LogWarning("DeleteAndMoveIntoHty:历史表实例 {HtyTypeName} 创建结果为null", htyTypeName); // return false; // } // // 3. 获取核心属性(指定BindingFlags确保获取公共实例属性) // BindingFlags propFlags = BindingFlags.Public | BindingFlags.Instance; // PropertyInfo? keyPro = typeof(TEntity).GetKeyProperty(); // 自定义方法需确保返回非空,此处增加判空 // PropertyInfo? operateTypePro = htyType.GetProperty(nameof(IBaseHistoryEntity.OperateType), propFlags); // PropertyInfo? sourceIdPro = htyType.GetProperty(nameof(IBaseHistoryEntity.SourceId), propFlags); // // 校验核心属性是否存在 // if (keyPro == null) // { // //_logger.LogError("DeleteAndMoveIntoHty:实体 {EntityType} 未找到主键属性", entityType.FullName); // return false; // } // if (operateTypePro == null) // { // //_logger.LogError("DeleteAndMoveIntoHty:历史表 {HtyTypeName} 未找到OperateType属性", htyTypeName); // return false; // } // if (sourceIdPro == null) // { // // _logger.LogError("DeleteAndMoveIntoHty:历史表 {HtyTypeName} 未找到SourceId属性", htyTypeName); // return false; // } // // 4. 赋值核心属性(校验类型匹配,避免SetValue抛异常) // try // { // // 处理OperateType类型匹配:若历史表属性是枚举类型,直接传枚举而非字符串 // if (operateTypePro.PropertyType == typeof(OperateTypeEnum)) // { // operateTypePro.SetValue(htyObj, operateType); // } // else if (operateTypePro.PropertyType == typeof(string)) // { // operateTypePro.SetValue(htyObj, operateType.ToString()); // } // else // { // //_logger.LogError("DeleteAndMoveIntoHty:历史表 {HtyTypeName} 的OperateType属性类型 {PropType} 不匹配(仅支持枚举/字符串)", htyTypeName, operateTypePro.PropertyType.FullName); // return false; // } // // 赋值SourceId(校验类型匹配) // object sourceIdValue = keyPro.GetValue(entity)!; // if (sourceIdPro.PropertyType != sourceIdValue.GetType()) // { // sourceIdValue = Convert.ChangeType(sourceIdValue, sourceIdPro.PropertyType); // 类型转换 // } // sourceIdPro.SetValue(htyObj, sourceIdValue); // } // catch (Exception ex) // { // // _logger.LogError(ex, "DeleteAndMoveIntoHty:历史表 {HtyTypeName} 核心属性赋值失败", htyTypeName); // return false; // } // // 5. 赋值其他属性(排除核心属性) // List htyProperties = htyType.GetProperties(propFlags) // .Where(x => x.Name != operateTypePro.Name // && x.Name != sourceIdPro.Name // && x.Name != keyPro.Name) // .ToList(); // foreach (PropertyInfo htyProp in htyProperties) // { // PropertyInfo? entityProp = entityType.GetProperty(htyProp.Name, propFlags); // if (entityProp == null) continue; // 实体无该属性则跳过 // try // { // object propValue; // // 处理修改人:避免App.User空引用 // if (htyProp.Name == nameof(BaseEntity.Modifier)) // { // propValue = App.User?.UserId > 0 ? App.User?.UserName : "System"; // } // // 处理修改时间 // else if (htyProp.Name == nameof(BaseEntity.ModifyDate)) // { // propValue = DateTime.Now; // } // // 其他属性从原实体取值 // else // { // propValue = entityProp.GetValue(entity) ?? DBNull.Value; // 处理null值 // } // // 类型转换后赋值(避免类型不匹配) // if (propValue != DBNull.Value && propValue != null) // { // propValue = Convert.ChangeType(propValue, htyProp.PropertyType); // } // htyProp.SetValue(htyObj, propValue); // } // catch (Exception ex) // { // // _logger.LogWarning(ex, "DeleteAndMoveIntoHty:历史表 {HtyTypeName} 属性 {PropName} 赋值失败,跳过该属性", htyTypeName, htyProp.Name); // } // } // try // { // // 执行插入历史表 // int insertRows = _db.InsertableByObject(htyObj).AS(entityType.Name + "_Hty").ExecuteCommand(); // if (insertRows <= 0) // { // // _logger.LogError("DeleteAndMoveIntoHty:历史表 {HtyTypeName} 插入失败(影响行数0)", htyTypeName); // _db.InsertableByObject(htyObj).AS(entityType.Name + "_Hty").ExecuteCommand(); // return false; // } // // 插入成功后执行删除 // bool deleteSuccess = DeleteData(entity); // if (!deleteSuccess) // { // //_logger.LogError("DeleteAndMoveIntoHty:实体 {EntityType} 删除失败", entityType.FullName); // DeleteData(entity); // return false; // } // // 提交事务 // isSuccess = true; // //_logger.LogInformation("DeleteAndMoveIntoHty:实体 {EntityType} 已成功移入历史表并删除原数据", entityType.FullName); // } // catch (Exception ex) // { // // _logger.LogError(ex, "DeleteAndMoveIntoHty:事务执行失败(插入历史表/删除原数据)", entityType.FullName); // return false; // } // } // catch (Exception ex) // { // // _logger.LogError(ex, "DeleteAndMoveIntoHty:处理实体 {EntityTypeName} 时发生未捕获异常", entityTypeName); // return false; // } // return isSuccess; //} public bool DeleteAndMoveIntoHty(List entities, OperateTypeEnum operateType) { Type type = typeof(TEntity); Assembly assembly = type.Assembly; Type? htyType = assembly.GetType(type.FullName + "_Hty"); if (htyType != null) { object? obj2 = Activator.CreateInstance(htyType); PropertyInfo keyPro = typeof(TEntity).GetKeyProperty(); PropertyInfo? operateTypePro = htyType.GetProperty(nameof(IBaseHistoryEntity.OperateType)); PropertyInfo? sourceIdPro = htyType.GetProperty(nameof(IBaseHistoryEntity.SourceId)); if (obj2 != null && keyPro != null && operateTypePro != null && sourceIdPro != null) { List propertyInfos = htyType.GetProperties().Where(x => x.Name != operateTypePro.Name && x.Name != sourceIdPro.Name && x.Name != keyPro.Name).ToList(); List list = new List(); foreach (var item in entities) { object? obj = Activator.CreateInstance(htyType); if (obj != null) { operateTypePro.SetValue(obj, operateType.ToString()); sourceIdPro.SetValue(obj, keyPro.GetValue(item)); for (int i = 0; i < propertyInfos.Count; i++) { PropertyInfo propertyInfo = propertyInfos[i]; PropertyInfo? property = type.GetProperty(propertyInfo.Name); if (property != null) { if (propertyInfo.Name == nameof(BaseEntity.Modifier)) { propertyInfo.SetValue(obj, App.User.UserId > 0 ? App.User.UserName : "System"); } else if (propertyInfo.Name == nameof(BaseEntity.ModifyDate)) { propertyInfo.SetValue(obj, DateTime.Now); } else { propertyInfo.SetValue(obj, property.GetValue(item)); } } } list.Add(obj); } } if (list.Count > 0) _db.InsertableByObject(list).AS(type.Name + "_Hty").ExecuteCommand(); } } return DeleteData(entities); } //List QueryMuch( // Expression> joinExpression, // Expression> selectExpression, // Expression> whereLambda = null) where T : class, new(){throw new NotImplementedException();} //Task> QueryPage(PaginationModel pagination){throw new NotImplementedException();} } }