重新SimpleClient<>的疑问 返回

SqlSugar 沟通中
2 589
该叫什么 Falcon 发布于2026/1/5
悬赏:0 飞吻

最新想实现数据逻辑删除功能,打算用重写仓储的方式实现。但是发现里面的Delete方法有很多,都要重写么?略显麻烦

~~~c#

    /// <summary>

    /// 数据仓储库

    /// </summary>

    /// <typeparam name="T">仓储理性</typeparam>

    public class DataRepository<T>:SimpleClient<T> where T : class, new()

    {

        /// <summary>

        /// 构造数据仓储

        /// </summary>

        /// <param name="db">数据访问客户端</param>

        public DataRepository(ISqlSugarClient db) {

            base.Context = db;

        }


        /// <inheritdoc/>

        public override bool Delete(T deleteObj) {

            if(deleteObj is ILogicDelete ld) {

                ld.IsDeleted = true;

                return base.Update(deleteObj);

            }

            return base.Delete(deleteObj);

        }


        public override bool Delete(List<T> deleteObjs) {

            return base.Delete(deleteObjs);

        }

    }

~~~

热忱回答(2)

  • 上面2个都需要重写。 

    0 回复
  • Falcon Falcon VIP0
    2026/1/5

    @fate sta:不止这两个。借助AI重写了400多行代码。

    using SqlSugar;
    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace His.Database.DataRepository
    {
    
        /// <summary>
        /// 基础逻辑删除接口(仅标记删除状态)
        /// </summary>
        public interface ILogicDelete
        {
            /// <summary>
            /// 逻辑删除标记(true=已删除,false=未删除)
            /// </summary>
            bool IsDeleted { get; set; }
        }
    
        /// <summary>
        /// 支持逻辑删除的 数据仓储库
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        public class DataRepository<T>:SimpleClient<T> where T : class, new()
        {
            public DataRepository() : base() {
            }
    
            public DataRepository(ISqlSugarClient context) : base(context) {
            }
    
            #region 同步删除方法
            public override bool Delete(T deleteObj) {
                if(deleteObj is ILogicDelete logicDeleteEntity) {
                    // 逻辑删除:更新IsDeleted标记
                    logicDeleteEntity.IsDeleted = true;
                    return Update(logicDeleteEntity as T);
                }
    
                // 未实现接口,执行物理删除
                return base.Delete(deleteObj);
            }
    
            public override bool Delete(List<T> deleteObjs) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    foreach(var obj in deleteObjs) {
                        if(obj is ILogicDelete logicDelete) {
                            logicDelete.IsDeleted = true;
                        }
                    }
                    return UpdateRange(deleteObjs);
                }
                return base.Delete(deleteObjs);
            }
    
            public override bool Delete(Expression<Func<T,bool>> whereExpression) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return Context.Updateable<T>()
                        .SetColumns(t => (t as ILogicDelete).IsDeleted == true)
                        .Where(whereExpression)
                        .ExecuteCommand() > 0;
                }
                return base.Delete(whereExpression);
            }
    
            public override bool DeleteById(dynamic id) {
                var entity = GetById(id);
                if(entity == null) return false;
                return Delete(entity);
            }
    
            public override bool DeleteByIds(dynamic[] ids) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return Context.Updateable<T>()
                        .SetColumns(t => (t as ILogicDelete).IsDeleted == true)
                        .In(ids)
                        .ExecuteCommand() > 0;
                }
                return base.DeleteByIds(ids);
            }
    
            public bool Delete(List<IConditionalModel> conditionalModels) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return Context.Updateable<T>()
                        .SetColumns(t => (t as ILogicDelete).IsDeleted == true)
                        .Where(conditionalModels)
                        .ExecuteCommand() > 0;
                }
    
                return base.Delete(conditionalModels);
            }
            #endregion
    
            #region 异步删除方法
            public override async Task<bool> DeleteAsync(T deleteObj) {
                if(deleteObj is ILogicDelete logicDeleteEntity) {
                    logicDeleteEntity.IsDeleted = true;
                    return await UpdateAsync(logicDeleteEntity as T);
                }
                return await base.DeleteAsync(deleteObj);
            }
    
            public override async Task<bool> DeleteAsync(List<T> deleteObjs) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    foreach(var obj in deleteObjs) {
                        if(obj is ILogicDelete logicDelete) {
                            logicDelete.IsDeleted = true;
                        }
                    }
                    return await UpdateRangeAsync(deleteObjs);
                }
                return await base.DeleteAsync(deleteObjs);
            }
    
            public override async Task<bool> DeleteAsync(Expression<Func<T,bool>> whereExpression) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return await Context.Updateable<T>()
                        .SetColumns(t => (t as ILogicDelete).IsDeleted == true)
                        .Where(whereExpression)
                        .ExecuteCommandAsync() > 0;
                }
                return await base.DeleteAsync(whereExpression);
            }
    
            public override async Task<bool> DeleteByIdAsync(dynamic id) {
                var entity = await GetByIdAsync(id);
                if(entity == null) return false;
                return await DeleteAsync(entity);
            }
    
            public override async Task<bool> DeleteByIdsAsync(dynamic[] ids) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return await Context.Updateable<T>()
                        .SetColumns(t => (t as ILogicDelete).IsDeleted == true)
                        .In(ids)
                        .ExecuteCommandAsync() > 0;
                }
                return await base.DeleteByIdsAsync(ids);
            }
    
            public override async Task<bool> DeleteAsync(T deleteObj,CancellationToken cancellationToken) {
                if(deleteObj is ILogicDelete logicDeleteEntity) {
                    logicDeleteEntity.IsDeleted = true;
                    return await UpdateAsync(logicDeleteEntity as T,cancellationToken);
                }
                return await base.DeleteAsync(deleteObj,cancellationToken);
            }
    
            public override async Task<bool> DeleteAsync(List<T> deleteObjs,CancellationToken cancellationToken) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    foreach(var obj in deleteObjs) {
                        if(obj is ILogicDelete logicDelete) {
                            logicDelete.IsDeleted = true;
                        }
                    }
                    return await UpdateRangeAsync(deleteObjs,cancellationToken);
                }
                return await base.DeleteAsync(deleteObjs,cancellationToken);
            }
    
            public override async Task<bool> DeleteAsync(Expression<Func<T,bool>> whereExpression,CancellationToken cancellationToken) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    Context.Ado.CancellationToken = cancellationToken;
                    return await Context.Updateable<T>()
                        .SetColumns(t => (t as ILogicDelete).IsDeleted == true)
                        .Where(whereExpression)
                        .ExecuteCommandAsync() > 0;
                }
                return await base.DeleteAsync(whereExpression,cancellationToken);
            }
    
            public override async Task<bool> DeleteByIdAsync(dynamic id,CancellationToken cancellationToken) {
                var entity = await GetByIdAsync(id,cancellationToken);
                if(entity == null) return false;
                return await DeleteAsync(entity,cancellationToken);
            }
    
            public override async Task<bool> DeleteByIdsAsync(dynamic[] ids,CancellationToken cancellationToken) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    Context.Ado.CancellationToken = cancellationToken;
                    return await Context.Updateable<T>()
                        .SetColumns(t => (t as ILogicDelete).IsDeleted == true)
                        .In(ids)
                        .ExecuteCommandAsync() > 0;
                }
    
                return await base.DeleteByIdsAsync(ids,cancellationToken);
            }
            #endregion
    
            #region 查询方法(自动过滤已删除数据)
            public override T GetSingle(Expression<Func<T,bool>> whereExpression) {
                return typeof(ILogicDelete).IsAssignableFrom(typeof(T))
                    ? base.GetSingle(CombineWithLogicDeleteFilter(whereExpression))
                    : base.GetSingle(whereExpression);
            }
    
            public override List<T> GetList(Expression<Func<T,bool>> whereExpression) {
                return typeof(ILogicDelete).IsAssignableFrom(typeof(T))
                    ? base.GetList(CombineWithLogicDeleteFilter(whereExpression))
                    : base.GetList(whereExpression);
            }
    
            public override bool IsAny(Expression<Func<T,bool>> whereExpression) {
                return typeof(ILogicDelete).IsAssignableFrom(typeof(T))
                    ? base.IsAny(CombineWithLogicDeleteFilter(whereExpression))
                    : base.IsAny(whereExpression);
            }
    
            public override int Count(Expression<Func<T,bool>> whereExpression) {
                return typeof(ILogicDelete).IsAssignableFrom(typeof(T))
                    ? base.Count(CombineWithLogicDeleteFilter(whereExpression))
                    : base.Count(whereExpression);
            }
    
            // 异步查询方法
            public override async Task<T> GetSingleAsync(Expression<Func<T,bool>> whereExpression) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return await base.GetSingleAsync(CombineWithLogicDeleteFilter(whereExpression));
                }
                return await base.GetSingleAsync(whereExpression);
            }
    
            public override async Task<List<T>> GetListAsync(Expression<Func<T,bool>> whereExpression) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return await base.GetListAsync(CombineWithLogicDeleteFilter(whereExpression));
                }
                return await base.GetListAsync(whereExpression);
            }
    
            public override async Task<bool> IsAnyAsync(Expression<Func<T,bool>> whereExpression) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return await base.IsAnyAsync(CombineWithLogicDeleteFilter(whereExpression));
                }
                return await base.IsAnyAsync(whereExpression);
            }
    
            public override async Task<int> CountAsync(Expression<Func<T,bool>> whereExpression) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    return await base.CountAsync(CombineWithLogicDeleteFilter(whereExpression));
                }
                return await base.CountAsync(whereExpression);
            }
    
            // 带CancellationToken的查询方法
            public override async Task<T> GetSingleAsync(Expression<Func<T,bool>> whereExpression,CancellationToken cancellationToken) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    Context.Ado.CancellationToken = cancellationToken;
                    return await base.GetSingleAsync(CombineWithLogicDeleteFilter(whereExpression),cancellationToken);
                }
                return await base.GetSingleAsync(whereExpression,cancellationToken);
            }
    
            public override async Task<List<T>> GetListAsync(Expression<Func<T,bool>> whereExpression,CancellationToken cancellationToken) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    Context.Ado.CancellationToken = cancellationToken;
                    return await base.GetListAsync(CombineWithLogicDeleteFilter(whereExpression),cancellationToken);
                }
                return await base.GetListAsync(whereExpression,cancellationToken);
            }
    
            public override async Task<bool> IsAnyAsync(Expression<Func<T,bool>> whereExpression,CancellationToken cancellationToken) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    Context.Ado.CancellationToken = cancellationToken;
                    return await base.IsAnyAsync(CombineWithLogicDeleteFilter(whereExpression),cancellationToken);
                }
                return await base.IsAnyAsync(whereExpression,cancellationToken);
            }
    
            public override async Task<int> CountAsync(Expression<Func<T,bool>> whereExpression,CancellationToken cancellationToken) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    Context.Ado.CancellationToken = cancellationToken;
                    return await base.CountAsync(CombineWithLogicDeleteFilter(whereExpression),cancellationToken);
                }
                return await base.CountAsync(whereExpression,cancellationToken);
            }
    
            // 补充基类其他查询方法
            public T GetSingle(List<IConditionalModel> conditionalModels) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    var combinedCondition = CombineConditionalModelWithLogicDelete(conditionalModels);
                    return base.GetSingle(combinedCondition);
                }
                return base.GetSingle(conditionalModels);
            }
    
            public List<T> GetList(List<IConditionalModel> conditionalList) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    var combinedCondition = CombineConditionalModelWithLogicDelete(conditionalList);
                    return base.GetList(combinedCondition);
                }
                return base.GetList(conditionalList);
            }
    
            public bool IsAny(List<IConditionalModel> conditionalModels) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    var combinedCondition = CombineConditionalModelWithLogicDelete(conditionalModels);
                    return base.IsAny(combinedCondition);
                }
                return base.IsAny(conditionalModels);
            }
    
            public int Count(List<IConditionalModel> conditionalModels) {
                if(typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    var combinedCondition = CombineConditionalModelWithLogicDelete(conditionalModels);
                    return base.Count(combinedCondition);
                }
                return base.Count(conditionalModels);
            }
            #endregion
    
            #region 逻辑删除恢复方法(扩展)
            /// <summary>
            /// 恢复逻辑删除的数据(仅对实现ILogicDelete接口的实体有效)
            /// </summary>
            /// <param name="id">主键值</param>
            /// <returns>是否恢复成功</returns>
            public bool RestoreById(object id) {
                ValidateLogicDeleteSupport();
                return Context.Updateable<T>()
                    .SetColumns(t => (t as ILogicDelete).IsDeleted == false)
                    .In(new object[] { id })
                    .ExecuteCommand() > 0;
            }
    
            /// <summary>
            /// 批量恢复逻辑删除的数据
            /// </summary>
            /// <param name="ids">主键集合</param>
            /// <returns>是否恢复成功</returns>
            public bool RestoreByIds(dynamic[] ids) {
                ValidateLogicDeleteSupport();
                return Context.Updateable<T>()
                    .SetColumns(t => (t as ILogicDelete).IsDeleted == false)
                    .In(ids)
                    .ExecuteCommand() > 0;
            }
    
            /// <summary>
            /// 根据条件恢复逻辑删除的数据
            /// </summary>
            /// <param name="whereExpression">条件表达式</param>
            /// <returns>是否恢复成功</returns>
            public bool Restore(Expression<Func<T,bool>> whereExpression) {
                ValidateLogicDeleteSupport();
                return Context.Updateable<T>()
                    .SetColumns(t => (t as ILogicDelete).IsDeleted == false)
                    .Where(whereExpression)
                    .ExecuteCommand() > 0;
            }
    
            /// <summary>
            /// 异步恢复逻辑删除的数据
            /// </summary>
            /// <param name="id">主键值</param>
            /// <returns>是否恢复成功</returns>
            public async Task<bool> RestoreByIdAsync(object id) {
                ValidateLogicDeleteSupport();
                return await Context.Updateable<T>()
                    .SetColumns(t => (t as ILogicDelete).IsDeleted == false)
                    .In(new object[] { id })
                    .ExecuteCommandAsync() > 0;
            }
    
            /// <summary>
            /// 异步批量恢复逻辑删除的数据
            /// </summary>
            /// <param name="ids">主键集合</param>
            /// <returns>是否恢复成功</returns>
            public async Task<bool> RestoreByIdsAsync(dynamic[] ids) {
                ValidateLogicDeleteSupport();
                return await Context.Updateable<T>()
                    .SetColumns(t => (t as ILogicDelete).IsDeleted == false)
                    .In(ids)
                    .ExecuteCommandAsync() > 0;
            }
    
            /// <summary>
            /// 异步根据条件恢复逻辑删除的数据
            /// </summary>
            /// <param name="whereExpression">条件表达式</param>
            /// <returns>是否恢复成功</returns>
            public async Task<bool> RestoreAsync(Expression<Func<T,bool>> whereExpression) {
                ValidateLogicDeleteSupport();
                return await Context.Updateable<T>()
                    .SetColumns(t => (t as ILogicDelete).IsDeleted == false)
                    .Where(whereExpression)
                    .ExecuteCommandAsync() > 0;
            }
    
            private void ValidateLogicDeleteSupport() {
                if(!typeof(ILogicDelete).IsAssignableFrom(typeof(T))) {
                    throw new NotSupportedException("当前实体未实现ILogicDelete接口,不支持逻辑删除恢复操作");
                }
            }
            #endregion
    
            #region 私有辅助方法
            /// <summary>
            /// 组合逻辑删除过滤条件(表达式)
            /// </summary>
            private Expression<Func<T,bool>> CombineWithLogicDeleteFilter(Expression<Func<T,bool>> originalExpression) {
                ParameterExpression parameter = Expression.Parameter(typeof(T),"t");
                MemberExpression isDeletedProperty = Expression.Property(parameter,nameof(ILogicDelete.IsDeleted));
                ConstantExpression falseValue = Expression.Constant(false,typeof(bool));
                Expression<Func<T,bool>> logicDeleteFilter = Expression.Lambda<Func<T,bool>>(
                    Expression.Equal(isDeletedProperty,falseValue),parameter);
    
                if(originalExpression == null) {
                    return logicDeleteFilter;
                }
    
                // 合并原始条件和逻辑删除条件(AND)
                var combined = Expression.Lambda<Func<T,bool>>(
                    Expression.AndAlso(
                        new ParameterReplacer(parameter).Visit(originalExpression.Body),
                        logicDeleteFilter.Body
                    ),parameter);
    
                return combined;
            }
    
            /// <summary>
            /// 组合逻辑删除过滤条件(IConditionalModel)
            /// </summary>
            private List<IConditionalModel> CombineConditionalModelWithLogicDelete(List<IConditionalModel> originalModels) {
                var combinedModels = originalModels ?? new List<IConditionalModel>();
                combinedModels.Add(new ConditionalModel {
                    FieldName = nameof(ILogicDelete.IsDeleted),
                    ConditionalType = ConditionalType.Equal,
                    FieldValue = false.ToString()
                });
                return combinedModels;
            }
    
            /// <summary>
            /// 参数表达式替换器(解决表达式参数不一致问题)
            /// </summary>
            private class ParameterReplacer:ExpressionVisitor
            {
                private readonly ParameterExpression _newParameter;
    
                public ParameterReplacer(ParameterExpression newParameter) {
                    _newParameter = newParameter;
                }
    
                protected override Expression VisitParameter(ParameterExpression node) {
                    return _newParameter;
                }
            }
            #endregion
        }
    }


    0 回复