You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: entity-framework/core/querying/filters.md
+92-53Lines changed: 92 additions & 53 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -7,83 +7,115 @@ uid: core/querying/filters
7
7
---
8
8
# Global Query Filters
9
9
10
-
Global query filters are LINQ query predicates applied to Entity Types in the metadata model (usually in `OnModelCreating`). A query predicate is a boolean expression typically passed to the LINQ `Where`query operator. EF Core applies such filters automatically to any LINQ queries involving those Entity Types. EF Core also applies them to Entity Types, referenced indirectly through use of Include or navigation property. Some common applications of this feature are:
10
+
Global query filters allow attaching a filter to an entity type and having that filter applied whenever a query on that entity type is executed; think of them as an additional LINQ `Where` operator that's added whenever the entity type is queried. Such filters are useful in a variety of cases.
11
11
12
-
***Soft delete** - An Entity Type defines an `IsDeleted` property.
13
-
***Multi-tenancy** - An Entity Type defines a `TenantId` property.
12
+
> [!TIP]
13
+
> You can view this article's [sample](https://github.com/dotnet/EntityFramework.Docs/tree/live/samples/core/Querying/QueryFilters) on GitHub.
14
14
15
-
## Example
15
+
## Basic example - soft deletion
16
16
17
-
The following example shows how to use Global Query Filters to implement multi-tenancy and soft-delete query behaviors in a simple blogging model.
17
+
In some scenarios, rather than deleting a row from the database, it's preferable to instead set an `IsDeleted` flag to mark the row as deleted; this pattern is called *soft deletion*. Soft deletion allows rows to be undeleted if needed, or to preserve an audit trail where deleted rows are still accessible. Global query filters can be used to filter out soft-deleted rows by default, while still allowing you to access them in specific places by disabling the filter for a specific query.
18
18
19
-
> [!TIP]
20
-
> You can view this article's [sample](https://github.com/dotnet/EntityFramework.Docs/tree/live/samples/core/Querying/QueryFilters) on GitHub.
19
+
To enable soft deletion, let's add an `IsDeleted` property to our Blog type:
21
20
22
-
> [!NOTE]
23
-
> Multi-tenancy is used here as a simple example. There is also an article with comprehensive guidance for [multi-tenancy in EF Core applications](xref:core/miscellaneous/multitenancy).
We now set up a global query filter, using the <xref:Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasQueryFilter*> API in `OnModelCreating`:
Note the declaration of a `_tenantId` field on the `Blog` entity. This field will be used to associate each Blog instance with a specific tenant. Also defined is an `IsDeleted`property on the `Post` entity type. This property is used to keep track of whether a post instance has been "soft-deleted". That is, the instance is marked as deleted without physically removing the underlying data.
27
+
We can now query our `Blog` entities as usual; the configured filter will ensure that all queries will - by default - filter out all instances where `IsDeleted` is true.
30
28
31
-
Next, configure the query filters in `OnModelCreating` using the `HasQueryFilter` API.
29
+
Note that at this point, you must manually set `IsDeleted`in order to soft-delete an entity. For a more end-to-end solution, you can override your context type's `SaveChangesAsync` method to add logic which goes over all entities which the user deleted, and changes them to be modified instead, setting the `IsDeleted` property to true:
The predicate expressions passed to the `HasQueryFilter` calls will now automatically be applied to any LINQ queries for those types.
33
+
This allows you to use EF APIs that delete an entity instance as usual and have them get soft-deleted instead.
36
34
37
-
> [!TIP]
38
-
> Note the use of a DbContext instance level field: `_tenantId` used to set the current tenant. Model-level filters will use the value from the correct context instance (that is, the instance that is executing the query).
35
+
## Using context data - multi-tenancy
39
36
40
-
> [!NOTE]
41
-
> It is currently not possible to define multiple query filters on the same entity - only the last one will be applied. However, you can define a single filter with multiple conditions using the logical `AND` operator ([`&&` in C#](/dotnet/csharp/language-reference/operators/boolean-logical-operators#conditional-logical-and-operator-)).
37
+
Another mainstream scenario for global query filters is *multi-tenancy*, where your application stores data belonging to different users in the same table. In such cases, there's usually a *tenant ID* column which associates the row to a specific tenant, and global query filters can be used to automatically filter for the rows of the current tenant. This provides strong tenant isolation for your queries by default, removing the need to think of filtering for the tenant in each and every query.
42
38
43
-
## Use of navigations
39
+
Unlike with soft deletion, multi-tenancy requires knowing the *current* tenant ID; this value is usually determined e.g. when the user authenticates over the web. For EF's purposes, the tenant ID must be available on the context instance, so that the global query filter can refer to it and use it when querying. Let's accept a `tenantId` parameter in our context type's constructor, and reference that from our filter:
44
40
45
-
You can also use navigations in defining global query filters. Using navigations in query filter will cause query filters to be applied recursively. When EF Core expands navigations used in query filters, it will also apply query filters defined on referenced entities.
This forces anyone constructing a context to specify its associated tenant ID, and ensures that only `Blog` entities with that ID are returned from queries by default.
46
52
47
-
To illustrate this configure query filters in `OnModelCreating` in the following way:
> This sample only showed basic multi-tenancy concepts needed in order to demonstrate global query filters. For more information on multi-tenancy and EF, see [multi-tenancy in EF Core applications](xref:core/miscellaneous/multitenancy).
This query produces the following SQL, which applies query filters defined for both `Blog` and `Post` entities:
58
+
Calling <xref:Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasQueryFilter*> with a simple filter overwrites any previous filter, so multiple filters **cannot** be defined on the same entity type in this way:
54
59
55
-
```sql
56
-
SELECT [b].[BlogId], [b].[Name], [b].[Url]
57
-
FROM [Blogs] AS [b]
58
-
WHERE (
59
-
SELECTCOUNT(*)
60
-
FROM [Posts] AS [p]
61
-
WHERE ([p].[Title] LIKE N'%fish%') AND ([b].[BlogId] = [p].[BlogId])) >0
> Currently EF Core does not detect cycles in global query filter definitions, so you should be careful when defining them. If specified incorrectly, cycles could lead to infinite loops during query translation.
69
+
> This feature is being introduced in EF Core 10.0 (in preview).
70
+
71
+
In order to define multiple query filters on the same entity type, they must be *named*:
## Accessing entity with query filter using required navigation
75
+
This allows you to manage each filter separately, including selectively disabling one but not the other.
76
+
77
+
### [Older versions](#tab/older)
78
+
79
+
Prior to EF 10, you can attach multiple filters to an entity type by calling <xref:Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasQueryFilter*> once and combining your filters using the `&&` operator:
This unfortunately does not allow to selectively disable a single filter.
86
+
87
+
***
88
+
89
+
## Disabling filters
90
+
91
+
Filters may be disabled for individual LINQ queries by using the <xref:Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.IgnoreQueryFilters*> operator:
If multiple named filters are configured, this disables all of them. To selectively disable specific filters (starting with EF 10), pass the list of filter names to be disabled:
> Using required navigation to access entity which has global query filter defined may lead to unexpected results.
71
103
72
-
Required navigation expects the related entity to always be present. If necessary related entity is filtered out by the query filter, the parent entity wouldn't be in result either. So you may get fewer elements than expected in result.
104
+
Required navigations in EF imply that the related entity is always present. Since inner joins may be used to fetch related entities, if a required related entity is filtered out by the query filter, the parent entity may get filtered out as well. This can result in unexpectedly retrieving fewer elements than expected.
73
105
74
-
To illustrate the problem, we can use the `Blog` and `Post` entities specified above and the following `OnModelCreating` method:
106
+
To illustrate the problem, we can use `Blog` and `Post` entities and configure them as follows:
With above setup, the first query returns all 6 `Post`s, however the second query only returns 3. This mismatch happens because `Include` method in the second query loads the related `Blog` entities. Since the navigation between `Blog` and `Post` is required, EF Core uses `INNER JOIN` when constructing the query:
118
+
With the above setup, the first query returns all 6 `Post` instances, but the second query returns only 3. This mismatch occurs because the`Include` method in the second query loads the related `Blog` entities. Since the navigation between `Blog` and `Post` is required, EF Core uses `INNER JOIN` when constructing the query:
Use of the `INNER JOIN` filters out all `Post`s whose related `Blog`s have been removed by a global query filter.
130
+
Use of the `INNER JOIN` filters out all `Post` rows whose related `Blog` rows have been filtered out by a query filter. This problem can be addressed by configuring the navigation as optional navigation instead of required, causing EF to generate a `LEFT JOIN` instead of an `INNER JOIN`:
99
131
100
-
It can be addressed by using optional navigation instead of required.
101
-
This way the first query stays the same as before, however the second query will now generate `LEFT JOIN` and return 6 results.
An alternative approach is to specify consistent filters on both `Blog` and `Post` entity types; once matching filters are applied to both `Blog` and `Post`, `Post` rows that could end up in unexpected state are removed and both queries return 3 results.
104
135
105
-
Alternative approach is to specify consistent filters on both `Blog` and `Post` entities.
106
-
This way matching filters are applied to both `Blog` and `Post`. `Post`s that could end up in unexpected state are removed and both queries return 3 results.
If your query filter needs to access a tenant ID or similar contextual information, <xref:Microsoft.EntityFrameworkCore.IEntityTypeConfiguration`1> can pose an additional complication as unlike with `OnModelCreating`, there's no instance of your context type readily available to reference from the query filter. As a workaround, add a dummy context to your configuration type and reference that as follows:
111
141
112
-
Filters may be disabled for individual LINQ queries by using the <xref:Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.IgnoreQueryFilters*> operator.
Global query filters have the following limitations:
119
157
120
-
* Filters can only be defined for the root Entity Type of an inheritance hierarchy.
158
+
* Filters can only be defined for the root entity type of an inheritance hierarchy.
159
+
* Currently EF Core does not detect cycles in global query filter definitions, so you should be careful when defining them. If specified incorrectly, cycles could lead to infinite loops during query translation.
Copy file name to clipboardExpand all lines: entity-framework/core/what-is-new/ef-core-10.0/whatsnew.md
+18-1Lines changed: 18 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -19,6 +19,22 @@ EF10 requires the .NET 10 SDK to build and requires the .NET 10 runtime to run.
19
19
20
20
<aname="cosmos"></a>
21
21
22
+
## Named query filters
23
+
24
+
EF's [global query filters](xref:core/querying/filters) feature has long enabled users to configuring filters to entity types which apply to all queries by default. This has simplified implementing common patterns and scenarios such as soft deletion, multitenancy and others. However, up to now EF has only supported a single query filter per entity type, making it difficult to have multiple filters and selectively disabling only some of them in specific queries.
25
+
26
+
EF 10 introduces *named query filters*, which allow attaching names to query filter and managing each one separately:
For more information on named query filters, see the [documentation](xref:core/querying/filters).
35
+
36
+
This feature was contributed by [@bittola](https://github.com/bittola).
37
+
22
38
## Azure Cosmos DB for NoSQL
23
39
24
40
<aname="full-text-search-support"></a>
@@ -130,7 +146,8 @@ See [#12793](https://github.com/dotnet/efcore/issues/12793) and [#35367](https:/
130
146
131
147
### Other query improvements
132
148
133
-
- Translate DateOnly.ToDateTime(timeOnly) ([#35194](https://github.com/dotnet/efcore/pull/35194), contributed by [@mseada94](https://github.com/mseada94)).
149
+
- Translate [DateOnly.ToDateTime()](/dotnet/api/system.dateonly.todatetime) ([#35194](https://github.com/dotnet/efcore/pull/35194), contributed by [@mseada94](https://github.com/mseada94)).
150
+
- Translate [DateOnly.DayNumber](/dotnet/api/system.dateonly.daynumber) and `DayNumber` subtraction for SQL Server and SQLite ([#36183](https://github.com/dotnet/efcore/issues/36183)).
134
151
- Optimize multiple consecutive `LIMIT`s ([#35384](https://github.com/dotnet/efcore/pull/35384), contributed by [@ranma42](https://github.com/ranma42)).
135
152
- Optimize use of `Count` operation on `ICollection<T>` ([#35381](https://github.com/dotnet/efcore/pull/35381), contributed by [@ChrisJollyAU](https://github.com/ChrisJollyAU)).
136
153
- Optimize `MIN`/`MAX` over `DISTINCT` ([#34699](https://github.com/dotnet/efcore/pull/34699), contributed by [@ranma42](https://github.com/ranma42)).
0 commit comments