& Lt; ABP framework & gt; data filtering, Data Filtering

Source: Internet
Author: User

<ABP framework> data filtering and Data Filtering in the abp framework

Document directory

 

Content of this section:

  • Introduction
  • Pre-defined Filtering
    • ISoftDelete
    • When is it available?
    • IMustHaveTenant
    • When is it available?
    • IMayHaveTenant
    • When is it available?
  • Disable Filtering
    • Using statement
    • About Multi-tenant
  • Enable Filtering
  • Set filter parameters
    • SetTenantId Method
  • Custom Filtering
    • EntityFramework. DynamicFilters documentation
  • Other ORM

 

Introduction

The soft Delete mode is usually used (if an object is not deleted from the database, it is just marked as "deleted"). If an object is deleted, it should not be accidentally obtained by the application. To provide this function, we should add a condition similar to "IsDeleted = false" to the where clause of each select query SQL statement, which is boring, but it is important and easy to forget, so an automatic method is required.

ABP provides data filtering, which can automatically filter queries based on these rules. Some pre-defined filters are available, but you can also create your own filters.

 

Pre-defined Filtering

ISoftDelete

The soft Delete filter is used to automatically filter (extracted from the results) deleted objects when querying the database. If an object can be soft deleted, it must implement the ISoftDelete interface, which defines only one IsDeleted attribute, for example:

public class Person : Entity, ISoftDelete{    public virtual string Name { get; set; }    public virtual bool IsDeleted { get; set; }}

In essence, a Person entity will not be deleted from the database. When you need to delete it, you just set its IsDeleted attribute to true. You can use IRepository. delete method (you can manually set IsDeleted to true, but the Delete method is more natural and recommended.

After ISoftDelete is implemented, When you obtain the Person list from the database, the soft Delete personnel will not be retrieved. Here is an example class, which uses a person warehouse to retrieve all the personnel:

public class MyService{    private readonly IRepository<Person> _personRepository;    public MyService(IRepository<Person> personRepository)    {        _personRepository = personRepository;    }    public List<Person> GetPeople()    {        return _personRepository.GetAllList();    }}

The GetPeople method only obtains all IsDeleted = false (not delete) persons. All warehousing methods and navigation attributes work properly. We can add some actually where conditions, connections, etc. It will automatically add the IsDeleted = false condition to the generated SQL query.

When is it available?

ISoftDelete filtering is always available unless you explicitly disable it.

Edge Note: If you implement IDeletionAudited (which extends ISoftDelete), The abcalso automatically assigns values to the deletion time and user ID.

 

IMustHaveTenant

If you are creating a multi-tenant application and storing all Tenant data in one database, you clearly do not want the data of one tenant to be accidentally seen by another tenant. In this case, you can use IMustHaveTenant. For example:

public class Product : Entity, IMustHaveTenant{    public int TenantId { get; set; }    public string Name { get; set; }}

IMustHaveTenant defines TenantId, which distinguishes different tenant entities. By default, you can use iabstmesion to obtain the current TenantId and automatically filter queries for the current tenant.

When is it available?

IMustHaveTenant is available by default.

If the current user has not logged on to the system or is currently a host user (the host user is a higher level user, which manages tenant and tenant data), the TTL automatically disables IMustHaveTenant filtering. Therefore, you can obtain all data of all tenants. Note: This is not related to security. You should always authorize sensitive data.

 

IMayHaveTenant

If an object class is shared by a tenant and a host (that is, an object can be owned by a tenant or host), you can use IMayHaveTenant to filter objects. The IMayHaveTenant interface defines TenantId, but it can be empty.

public class Role : Entity, IMayHaveTenant{    public int? TenantId { get; set; }    public string RoleName { get; set; }}

A null value indicates that this is a host entity. A non-null value indicates that this entity is owned by a tenant whose Id is TenantId. By default, ABP uses iabstmesion to obtain the current TenantId. IMayHaveTenant filtering is not as common as IMustHaveTenant, but is required when entity types are common hosts and tenants.

How is it available?

IMayHaveTenant is always available unless you explicitly disable it.

 

Disable Filtering

You can call the DisableFilter method to disable one filter for each unit of work, as follows:

var people1 = _personRepository.GetAllList();using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete)){    var people2 = _personRepository.GetAllList();                }var people3 = _personRepository.GetAllList();

DisableFilter accepts a string composed of one or more filter names. AbpDataFilters. SoftDelete is a String constant, which represents the soft deletion filter of ABP.

People2 will include the soft-deleted people, And people1 and people3 will only contain the people that are not soft-deleted. With the using declaration, you can disable a filter in the using domain. If you do not use the using declaration, the filter will be disabled until the current work unit ends or you will see that this filter is enabled.

You can inject IUnitOfWorkManager and use it as in the previous example. If your class inherits from a special base class (such as application service, AbpController, AbpApiController ...), you can also directly use the CurrentUnitOfWork attribute.

Using statement

If a filter is enabled, when you use the using declaration and call the DisableFilter method, the filter will be disabled and automatically enabled after the using declaration. However, if this filter is disabled before using declaration, then DisableFilter does not do anything. After using declaration, it is still disabled.

About Multi-tenant

You can disable multi-tenant filtering to query data of all tenants, but this is only valid for one database. If you use a separate database for each tenant, disabling filtering cannot help you obtain data from all tenants, because the data is stored in different databases or even on different servers, for more information, see the multi-tenant document.

 

Enable Filtering

In a work unit, you can use the EnableFilter method to enable a filter. Similar to (and opposite to) DisableFilter. EnableFilter also returns releasable objects when using declaration is used to re-Disable filtering if necessary.

 

Set filter parameters

One filter can be parameterized. IMusthaveTenant filtering is an example because the Id of the current tenant can be detected at runtime. For such filtering, we can modify the filtering value if necessary, such:

CurrentUnitOfWork.SetFilterParameter("PersonFilter", "personId", 42);

Another example: Filter IMayHaveTenant and set the tenant Id:

CurrentUnitOfWork.SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, 42);

The SetFilterParameter method also returns an IDisposeble, So it uses a using declaration to automatically restore the original value after the declaration.

 

SetTenantId Method

Although you can use the SetFilterParameter method to modify the filter value for MayHaveTenant and MusthaveTenant, there is a better way to modify the tenant filter: SetTenantId (). SetTenantId filters and modifies the parameter values for these two filters, and the values are valid for a single database or for each tenant and one Database. Therefore, it is always recommended to use SetTenantId to modify the parameter values filtered by tenants. View the multi-tenant document for more information.

 

Custom Filtering

To customize the filtering and integrate the filtering into the ABP, first define an interface that will be implemented using the filtering entity. Suppose we want to use the PersonId to automatically filter objects. The interface Example is as follows:

public interface IHasPerson{    int PersonId { get; set; }}

Then we implement this interface for the desired object. entity example:

public class Phone : Entity, IHasPerson{    [ForeignKey("PersonId")]    public virtual Person Person { get; set; }    public virtual int PersonId { get; set; }    public virtual string Number { get; set; }}

Because ABC uses EntityFramework. DynamicFilters, we use its rules to define this filter. In our DbContext class, we override OnModelCreating, as shown below:

protected override void OnModelCreating(DbModelBuilder modelBuilder){    base.OnModelCreating(modelBuilder);    modelBuilder.Filter("PersonFilter", (IHasPerson entity, int personId) => entity.PersonId == personId, 0);}

"PersonFilter" is the unique name for this filtering. The second parameter indicates the filtering interface and the filtering parameter PersonId (if the filtering cannot be parameterized, it is not required). The last parameter is the default value of personId.

Finally, in the PreInitialize method of our module, register this filter to the ABP work unit system:

Configuration.UnitOfWork.RegisterFilter("PersonFilter", false);

The first parameter is the name we previously defined, and the second parameter specifies whether to enable it by default. After declaring such a parameterized filter, we use it and give it a value at runtime:

using (CurrentUnitOfWork.EnableFilter("PersonFilter")){    using(CurrentUnitOfWork.SetFilterParameter("PersonFilter", "personId", 42))    {        var phones = _phoneRepository.GetAllList();        //...    }}

We should get the personId from other places instead of hard encoding. The above is an example of parameterized filtering. A filtering may have 0 or more parameters. If there are no parameters, it is not necessary to set the filtered parameter values. Similarly, if the default filter is enabled, you do not have to manually enable it (of course, we can disable it ).

EntityFramework. DynamicFilters documentation

For more information about dynamic data filtering, see the documentation on the github page: https://github.com/jcachat/EntityFramework.DynamicFilters

We can customize Filtering for security, active/passive, and other entities.

 

Other ORM

TTL data filtering is implemented by EntityFramework and nhib.pdf. It cannot be used on other ORM systems (including EntityFramework Core ). But in essence, you can imitate it in most cases. As long as you also use warehousing to obtain data, you can customize a warehousing, and then rewrite GetAll and other required data acquisition methods.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.