<<ABP Framework >> Data filtering

Source: Internet
Author: User
Tags app service

Document Directory

The content of this section:

    • Brief introduction
    • Pre-defined filtering
      • Isoftdelete
      • When is it available?
      • Imusthavetenant
      • When is it available?
      • Imayhavetenant
      • When is it available?
    • Disable filtering
      • about using declarations
      • About multi-tenancy
    • Enable filtering
    • Setting Filter Parameters
      • Settenantid method
    • Custom filtering
      • Entityframework.dynamicfilters Documentation
    • Other ORM

Brief introduction

Usually use the soft-delete mode (do not delete an entity from the database, just give it a flag "deleted"), if an entity is soft deleted, it should not be applied accidentally obtained, in order to provide this function, we should add a similar "in the Where of the SQL statement for each select query" Isdeleted=false "conditions, which are boring, but also very important and easy to forget, so need an automatic way.

The ABP provides data filtering that can automatically filter queries based on these rules. There are some pre-defined filters, but you can also create your own filters.

Pre-defined filtering

Isoftdelete

Soft-delete filtering is used to automatically filter (extract from results) deleted entities when querying the database. If an entity 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 ; Span style= "color: #0000ff;" >set      ;}  }

Essentially does not delete a person entity from the database, when it is necessary to delete it, just set its IsDeleted property to True, You can use the Irepository.delete method (you can manually set IsDeleted to True, but the Delete method is more natural and recommended) to complete.

After implementing Isoftdelete, when you get the person list from the database, the soft-deleted people will not be fetched, there is an example class here, using a person repository to get all the people:

 Public class myservice{    privatereadonly irepository<person> _personrepository;      Public MyService (irepository<person> personrepository)    {        = personrepository;    }      Public List<person> GetPeople ()    {        return  _personrepository.getalllist ();    }}

The Getpeople method only gets the person with all isdeleted=false (not delete). All warehousing methods and navigation properties are working properly. We can add some actually where conditions, joins, etc., and 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.

Side Note: If you implement ideletionaudited (which expands the Isoftdelete), the ABP will also automatically assign a value to delete time and delete user ID.

Imusthavetenant

If you are creating a multi-tenant app and storing all tenant data in one database, you explicitly do not want the data of one tenant to be accidentally seen by another tenant, in which case you can use Imusthavetenant. For example:

 Public class  imusthavetenant{    publicintgetset;}  Public    stringgetset;}

Imusthavetenant defines the Tenantid and distinguishes between different tenant entities. The ABP uses iabpseesion to get the current Tenantid by default and automatically filters queries for the current tenant.

When is it available?

Imusthavetenant is available by default.

If the current user is not logged on to the system or is currently a host user (the host user is a higher-level user, it manages tenant and tenant data), the ABP automatically disables imusthavetenant filtering, so that all data for all tenants can be obtained. Note: This is not related to security, you should always authorize sensitive data.

Imayhavetenant

If an entity class is shared by tenants and hosts (that is, an entity object can be owned by a tenant or host), you can use imayhavetenant filtering. The Imayhavetenant interface defines the Tenantid, but it is nullable.

 Public class  imayhavetenant{    publicintgetset;}  Public    stringgetset;}

A null value indicates that this is a host entity, and a non-null value indicates that the entity is owned by a tenant with ID tenantid. By default, the ABP uses iabpseesion to get the current tenantid. Imayhavetenant filtering is not as generic as imusthavetenant, but it is required when the entity type is common to hosts and tenants.

How is it available?

Imayhavetenant is always available unless you explicitly disable it.

Disable filtering

Call the Disablefilter method to disable a 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 consisting of one or more filter names, and Abpdatafilters.softdelete is a string constant that represents the soft-delete filter for the ABP.

People2 will contain soft-deleted people,people1 and people3 contain only people that have not been soft-deleted. With the using declaration, you can disable a filter within the using domain. If you do not use a using declaration, the filter is disabled until the current unit of work is finished or you display enable this filter.

You can inject Iunitofworkmanager and then use it as in the example above if your class inherits from a special base class (such as App service, Abpcontroller,abpapicontroller ... ), you can also use the Currentunitofwork property directly.

about using declarations

If a filter is enabled, when you use the using declaration to invoke the Disablefilter method, the filter is disabled and then automatically enabled after the using declaration. However, if this filter is disabled before using the use declaration, then disablefilter does nothing, and after the using declaration it is still disabled.

About multi-tenancy

You can disable multi-tenancy filtering to query data for all tenants, but this is only valid for one database. If you use separate databases for each tenant, disabling filtering will not help you get all of your tenant's data, because the data is in different databases or even different servers, more information to view multi-tenancy documents.

Enable filtering

In a unit of work, you can use the Enablefilter method to enable a filter. Similar to (also contrary to) disablefilter. Enablefilter also uses a using declaration to return a disposable object that is used to re-disable filtering if necessary.

Setting Filter Parameters

A filter can be parameterized, imusthavetenant filtering is an example, because the ID of the current tenant can be detected at run time. For this type of filtering, we can modify the filter values if necessary, such as:

Currentunitofwork.setfilterparameter ("personfilter""personId"  );

Another example: For imayhavetenant filtering, set the tenant ID:

);

The Setfilterparameter method also returns a idisposeble, so use a using declaration that automatically restores the original value after the declaration.

Settenantid method

Although you can use the Setfilterparameter method to modify filter values for Mayhavetenant and musthavetenant, there is a better way to modify tenant filtering: Settenantid (). Settenantid modifies the parameter values for both filters, and a single database or one database per tenant is valid. Therefore, it is always recommended to modify the parameter values of the tenant filter with Settenantid. See Multi-tenancy documentation for more information.

Custom filtering

For custom filtering and integration into the ABP, first, define an interface that will be implemented using this filtered entity. Let's say we want to automatically filter entities through PersonID, interface examples:

 Public Interface ihasperson{    intgetset;}}

Then we implement this interface for the required entities, the entity example:

 Public classphone:entity, ihasperson{[ForeignKey ("PersonId")]     Public VirtualPerson Person {Get;Set; }  Public Virtual intPersonId {Get;Set; }  Public Virtual stringNumber {Get;Set; }}

Because ABP uses entityframework.dynamicfilters, we use its rules to define this filter, in our DbContext class, we rewrite onmodelcreating as follows:

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) {    base. Onmodelcreating (ModelBuilder);    Modelbuilder.filter (   "personfilter"int0  );}

"Personfilter" is the only name for this filter, and the second parameter indicates the filtered interface and filter Parameters PersonID (if the filter is not parameterized, not available), the last parameter is the default value of PersonID.

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

Configuration.UnitOfWork.RegisterFilter ("personfilter"false);

The first parameter is the name we defined earlier, and the second parameter indicates whether it is enabled by default. After declaring such a parameterized filter, we use it and give it a value at run time:

using(Currentunitofwork.enablefilter ("personfilter" )){    using(Currentunitofwork.setfilterparameter ("personfilter", "personId ",  ))    {        varPhones =_phonerepository.getalllist (); //...    }}

We should obtain PersonID from other places instead of hard coding. The above is a parameterized filter example, a filter may have 0 or more parameters, if there is no parameter, there is no need to set the filter parameter value, 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 on dynamic Data filtering, see the documentation on the GitHub page: https://github.com/jcachat/EntityFramework.DynamicFilters

We can customize filtering for entities such as security, active/passive, and so on.

Other ORM

ABP data filtering is implemented for EntityFramework and NHibernate and is not available on other ORM (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.

<<ABP Framework >> Data filtering

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.