Data Filtering

Volo.Abp.Data package defines services to automatically filter data on querying from a database.

Pre-Defined Filters

ABP defines some filters out of the box.

ISoftDelete

Used to mark an entity as deleted instead of actually deleting it. Implement the ISoftDelete interface to make your entity “soft delete”.

Example:

  1. using System;
  2. using Volo.Abp;
  3. using Volo.Abp.Domain.Entities;
  4. namespace Acme.BookStore
  5. {
  6. public class Book : AggregateRoot<Guid>, ISoftDelete
  7. {
  8. public string Name { get; set; }
  9. public bool IsDeleted { get; set; } //Defined by ISoftDelete
  10. }
  11. }

ISoftDelete defines the IsDeleted property. When you delete a book using repositories, ABP automatically sets IsDeleted to true and protects it from actual deletion (you can also manually set the IsDeleted property to true if you need). In addition, it automatically filters deleted entities when you query the database.

ISoftDelete filter is enabled by default and you can not get deleted entities from database unless you explicitly disable it. See the IDataFilter service below.

IMultiTenant

Multi-tenancy is an efficient way of creating SaaS applications. Once you create a multi-tenant application, you typically want to isolate data between tenants. Implement IMultiTenant interface to make your entity “multi-tenant aware”.

Example:

  1. using System;
  2. using Volo.Abp;
  3. using Volo.Abp.Domain.Entities;
  4. using Volo.Abp.MultiTenancy;
  5. namespace Acme.BookStore
  6. {
  7. public class Book : AggregateRoot<Guid>, ISoftDelete, IMultiTenant
  8. {
  9. public string Name { get; set; }
  10. public bool IsDeleted { get; set; } //Defined by ISoftDelete
  11. public Guid? TenantId { get; set; } //Defined by IMultiTenant
  12. }
  13. }

IMultiTenant interface defines the TenantId property which is then used to automatically filter the entities for the current tenant. See the Multi-tenancy document for more.

IDataFilter Service: Enable/Disable Data Filters

You can control the filters using IDataFilter service.

Example:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Volo.Abp;
  5. using Volo.Abp.Data;
  6. using Volo.Abp.DependencyInjection;
  7. using Volo.Abp.Domain.Repositories;
  8. namespace Acme.BookStore
  9. {
  10. public class MyBookService : ITransientDependency
  11. {
  12. private readonly IDataFilter _dataFilter;
  13. private readonly IRepository<Book, Guid> _bookRepository;
  14. public MyBookService(
  15. IDataFilter dataFilter,
  16. IRepository<Book, Guid> bookRepository)
  17. {
  18. _dataFilter = dataFilter;
  19. _bookRepository = bookRepository;
  20. }
  21. public async Task<List<Book>> GetAllBooksIncludingDeletedAsync()
  22. {
  23. //Temporary disable the ISoftDelete filter
  24. using (_dataFilter.Disable<ISoftDelete>())
  25. {
  26. return await _bookRepository.GetListAsync();
  27. }
  28. }
  29. }
  30. }
  • Inject the IDataFilter service to your class.
  • Use the Disable method within a using statement to create a code block where the ISoftDelete filter is disabled inside it (Always use it inside a using block to guarantee that the filter is reset to its previous state).

IDataFilter.Enable method can be used to enable a filter. Enable and Disable methods can be used in a nested way to define inner scopes.

AbpDataFilterOptions

AbpDataFilterOptions can be used to set options for the data filter system.

The example code below disables the ISoftDelete filter by default which will cause to include deleted entities when you query the database unless you explicitly enable the filter:

  1. Configure<AbpDataFilterOptions>(options =>
  2. {
  3. options.DefaultStates[typeof(ISoftDelete)] = new DataFilterState(isEnabled: false);
  4. });

Carefully change defaults for global filters, especially if you are using a pre-built module which might be developed assuming the soft delete filter is turned on by default. But you can do it for your own defined filters safely.

Defining Custom Filters

Defining and implementing a new filter highly depends on the database provider. ABP implements all pre-defined filters for all database providers.

When you need it, start by defining an interface (like ISoftDelete and IMultiTenant) for your filter and implement it for your entities.

Example:

  1. public interface IIsActive
  2. {
  3. bool IsActive { get; }
  4. }

Such an IIsActive interface can be used to filter active/passive data and can be easily implemented by any entity:

  1. public class Book : AggregateRoot<Guid>, IIsActive
  2. {
  3. public string Name { get; set; }
  4. public bool IsActive { get; set; } //Defined by IIsActive
  5. }

EntityFramework Core

ABP uses EF Core’s Global Query Filters system for the EF Core Integration. So, it is well integrated to EF Core and works as expected even if you directly work with DbContext.

Best way to implement a custom filter is to override CreateFilterExpression method for your DbContext. Example:

  1. protected bool IsActiveFilterEnabled => DataFilter?.IsEnabled<IIsActive>() ?? false;
  2. protected override Expression<Func<TEntity, bool>> CreateFilterExpression<TEntity>()
  3. {
  4. var expression = base.CreateFilterExpression<TEntity>();
  5. if (typeof(IIsActive).IsAssignableFrom(typeof(TEntity)))
  6. {
  7. Expression<Func<TEntity, bool>> isActiveFilter =
  8. e => !IsActiveFilterEnabled || EF.Property<bool>(e, "IsActive");
  9. expression = expression == null
  10. ? isActiveFilter
  11. : CombineExpressions(expression, isActiveFilter);
  12. }
  13. return expression;
  14. }
  • Added a IsActiveFilterEnabled property to check if IIsActive is enabled or not. It internally uses the IDataFilter service introduced before.
  • Overrided the CreateFilterExpression method, checked if given entity implements the IIsActive interface and combines the expressions if necessary.

MongoDB

ABP implements data filters directly in the repository level for the MongoDB Integration. So, it works only if you use the repositories properly. Otherwise, you should manually filter the data.

Currently, the best way to implement a data filter for the MongoDB integration is to override the AddGlobalFilters in the repository derived from the MongoDbRepository class. Example:

  1. public class BookRepository : MongoDbRepository<BookStoreMongoDbContext, Book, Guid>
  2. {
  3. protected override void AddGlobalFilters(List<FilterDefinition<Book>> filters)
  4. {
  5. if (DataFilter.IsEnabled<IIsActive>())
  6. {
  7. filters.Add(Builders<Book>.Filter.Eq(e => ((IIsActive)e).IsActive, true));
  8. }
  9. }
  10. }

This example implements it only for the Book entity. If you want to implement for all entities (those implement the IIsActive interface), create your own custom MongoDB repository base class and override the AddGlobalFilters as shown below:

  1. public abstract class MyMongoRepository<TMongoDbContext, TEntity, TKey> : MongoDbRepository<TMongoDbContext, TEntity, TKey>
  2. where TMongoDbContext : IAbpMongoDbContext
  3. where TEntity : class, IEntity<TKey>
  4. {
  5. protected MyMongoRepository(IMongoDbContextProvider<TMongoDbContext> dbContextProvider)
  6. : base(dbContextProvider)
  7. {
  8. }
  9. protected override void AddGlobalFilters(List<FilterDefinition<TEntity>> filters)
  10. {
  11. if (typeof(IIsActive).IsAssignableFrom(typeof(TEntity))
  12. && DataFilter.IsEnabled<IIsActive>())
  13. {
  14. filters.Add(Builders<TEntity>.Filter.Eq(e => ((IIsActive)e).IsActive, true));
  15. }
  16. }
  17. }

See “Set Default Repository Classes” section of the MongoDb Integration document to learn how to replace default repository base with your custom class.