Introduction
This feature is also called a model-level query filter. It allows us to specify a filter in the model level that is automatically applied to all queries that are executed in the context of the specified type. It means that the entity framework automatically adds the filter in the where clause before executing the LINQ queries. Usually, global query filters are applied in the OnModelCreating method of the context. These filters are also automatically applied to LINQ queries involving entity types that are indirectly referenced, such as ones included as a navigation property.
Common uses of this feature are.
- Soft delete: an Entity Type defines an IsDeleted property, and the application does not require deleted data.
- Multi-tenancy: an Entity Type defines a TenantId property
Example
The following example shows how to apply a global query filter to implement soft-delete. To demonstrate the example, I have created an Employee table and it has the IsDeleted column that is used to define whether the record is deleted or not.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
[Id] [int] NOT NULL,
NULL,
[IsDeleted] [bit] NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[Id] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[Employee] ([Id], [Name], [IsDeleted]) VALUES (1, N'Jignesh', 0)
INSERT [dbo].[Employee] ([Id], [Name], [IsDeleted]) VALUES (2, N'Rakesh', 0)
INSERT [dbo].[Employee] ([Id], [Name], [IsDeleted]) VALUES (3, N'Tejas', 0)
INSERT [dbo].[Employee] ([Id], [Name], [IsDeleted]) VALUES (4, N'Rajesh', 1)

First, define entities and context class.
Employee. cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace GlobalFilterExample.Model
{
[Table("Employee")]
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public bool IsDeleted { get; set; }
}
}
EntityModelContext.cs



Michael McCoyPosted May 7, 2018, 8:59 AM
Straight lift from Microsoft documentation. Plagiarism... https://docs.microsoft.com/en-us/ef/core/querying/filters Pointless article to raise personal profile.
Naresh SinghalPosted Mar 4, 2018, 10:28 PM
Nice Sir............