Use el filtro Abp para realizar la función de "papelera de reciclaje" de datos comerciales

principio

La papelera de reciclaje es cuando un usuario elimina un registro, en lugar de eliminarlo directamente de la base de datos, se coloca en la "papelera de reciclaje" para que el usuario pueda restaurar los datos cuando sea necesario.

En el marco Abp, si la entidad implementa ISoftDelete, marcar la entidad para su eliminación no es una eliminación física, sino una "eliminación suave"

public interface ISoftDelete
{
    /// <summary>
    /// Used to mark an Entity as 'Deleted'. 
    /// </summary>
    bool IsDeleted { get; set; }
}

Al usar el repositorio para eliminar un registro, ABP configurará automáticamente IsDeleted como verdadero y reemplazará la operación de eliminación con la operación de modificación. Las entidades eliminadas temporalmente se filtran automáticamente al consultar la base de datos.

Usando este principio, el comportamiento de "eliminación temporal" se puede considerar que se coloca en la "papelera de reciclaje" y el comportamiento de "recuperación" se puede considerar que se retira de la "papelera de reciclaje". El acto de eliminar registros de forma permanente se considera "eliminación permanente", y la eliminación definitiva de todos los registros "eliminados temporalmente" es "vaciar la papelera de reciclaje".

Entonces necesito implementar un filtro personalizado para ver las entidades eliminadas.

crear filtro

Defina un filtro para ver solo las eliminaciones temporales, llamado "OnlyShowSoftDelete"

public class FileDataFilters
{
    public const string OnlyShowSoftDelete = "OnlyShowSoftDelete";

}

Registre el filtro en el módulo, el parámetro isEnabledByDefault es falso y no está habilitado por defecto

Configuration.UnitOfWork.RegisterFilter(FileDataFilters.OnlyShowSoftDelete, false);

En DbContext, agregue el atributo IsOnlyShowSoftDeleteFilterEnabled para determinar si el filtro "solo ver eliminación temporal" está habilitado en el contexto de consulta actual

public bool IsOnlyShowSoftDeleteFilterEnabled => CurrentUnitOfWorkProvider?.Current?.IsFilterEnabled(FileStorage.Uow.FileDataFilters.OnlyShowSoftDelete) == true;

En DbContext, invalide el método CreateFilterExpression para filtrar automáticamente las entidades eliminadas temporalmente cuando el filtro "solo ver las eliminadas temporalmente" está habilitado

protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
{
    var expression = base.CreateFilterExpression<TEntity>();
    if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
    {
        Expression<Func<TEntity, bool>> softDeleteFilter = e => !IsOnlyShowSoftDeleteFilterEnabled || ((ISoftDelete)e).IsDeleted;
        expression = expression == null ? softDeleteFilter : CombineExpressions(expression, softDeleteFilter);
    }

    return expression;
}

usar filtro

Preguntar

Al consultar negocios normales, no es necesario operar en el filtro predeterminado.

Al ver los datos en la "Papelera de reciclaje", debe desactivar el filtro AbpDataFilters.SoftDelete y activar el filtro FileDataFilters.OnlyShowSoftDelete.

Antes de realizar cualquier consulta (por ejemplo, GetAll o Get) utilizando el repositorio, agregue el siguiente código:

UnitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete);
UnitOfWorkManager.Current.EnableFilter(FileDataFilters.OnlyShowSoftDelete);

borrar

Al eliminar un registro, el registro se coloca en la "papelera de reciclaje" llamando al método Delete() del repositorio. Llame al método HardDelete() para eliminar permanentemente el registro.


public virtual async Task DeleteAsync(File file, bool isHardDelete = false)
{
    if (isHardDelete)
    {
        await _repository.HardDeleteAsync(file);  //永久删除
    }
    else
    {
        await _repository.DeleteAsync(file);       //放入“回收站”
    }
}

recuperar

Obtenga los registros que se han "eliminado temporalmente", llame al método UnDelete() y saque los registros de la "papelera de reciclaje"

UnitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete);
UnitOfWorkManager.Current.EnableFilter(FileDataFilters.OnlyShowSoftDelete);

var currentFile = await _repository.GetAsync(file.Id);
currentFile.UnDelete();

Configuración del controlador para la nueva versión de Volo.Abp

La nueva versión de Volo.Abp cancela el método de configuración de cadenas y necesita especificar una interfaz para el controlador.

Cree la interfaz IOnlyShowSoftDelete:

public interface IOnlyShowSoftDelete
{
}

Agregar configuración para establecer el estado predeterminado del controlador en no habilitado

Configure<AbpDataFilterOptions>(options =>
{
    options.DefaultStates[typeof(IOnlyShowSoftDelete)] = new DataFilterState(isEnabled: false);
});

De manera similar, en DbContext, anule el método CreateFilterExpression para filtrar automáticamente las entidades eliminadas temporalmente cuando el filtro "solo ver eliminado temporalmente" está habilitado

protected bool IsOnlyShowSoftDeleteFilterEnabled => DataFilter?.IsEnabled<IOnlyShowSoftDelete>() ?? false;

protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
{
    var expression = base.CreateFilterExpression<TEntity>();

    if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity)))
    {
        Expression<Func<TEntity, bool>> softDeleteFilter = e => !IsOnlyShowSoftDeleteFilterEnabled || ((ISoftDelete)e).IsDeleted;
        expression = expression == null ? softDeleteFilter : CombineExpressions(expression, softDeleteFilter);
    }

    return expression;
}


Inyecte el servicio IDataFilter en su clase

private readonly IDataFilter _dataFilter;

public MyBookService(IDataFilter dataFilter)
{
    _dataFilter = dataFilter;
}

Use los métodos Habilitar y Deshabilitar de _dataFilter para habilitar o deshabilitar el filtro


public async Task<List<Book>> GetAllBooksAsync()
{
    if(input.IncludeTrash)
    {
        //临时显示软删除的记录
        using ( _dataFilter.Disable<ISoftDelete>())
        using ( _dataFilter.Enable<IOnlyShowSoftDelete>())
        {
            return await _bookRepository.GetListAsync();
        }
    }
    else
    {
        return await _bookRepository.GetListAsync();
    }
}

O use UnitOfWorkManager para resolver el servicio IDataFilter

using (input.IncludeTrash ? this.UnitOfWorkManager.Current.ServiceProvider.GetRequiredService<IDataFilter<ISoftDelete>>().Disable() : NullDisposable.Instance)
using (input.IncludeTrash ? this.UnitOfWorkManager.Current.ServiceProvider.GetRequiredService<IDataFilter<IOnlyShowSoftDelete>>().Enable() : NullDisposable.Instance)
{
    return await _bookRepository.GetListAsync();
}

Supongo que te gusta

Origin blog.csdn.net/jevonsflash/article/details/131802169
Recomendado
Clasificación