مرشحات الاستعلام في Entity Framework Core و ASP.NET
One of the main reasons I like ASP.NET so much is that it has great tooling for working with data. Entity Framework is the standard ORM in the ASP.NET framework. EF provides powerful features like LINQ queries, migrations, ، و change tracking. These features allow developers to create sophisticated business applications with relative ease.
A powerful yet lesser-known feature in Entity Framework is query filtering. Query filters enable developers to set global data retrieval conditions. It’s like adding a WHERE clause to every query, but only needing to do it in one place. If you are trying to learn how to build multitenant apps, understanding the capabilities of query filters is essential. Definitely check out the نموذج Nano ASP.NET which implements the concepts covered in this tutorial and many more, with complete الوثائق.
In this article we will implement a soft-delete feature with the help of query filters. Soft deletion is a common feature in many applications, that when a user deletes a record from the database, its not actually removed, but rather marked as deleted. Later, when retrieving records, the entities marked as deleted are not returned. This approach provides the ability to retain data for historical or auditing purposes while maintaining data integrity.
A soft-delete feature is small in scope and complexity but demonstrates the core functionality of query filters. Once you understand the fundamentals of query filters, you will begin to see how they could be used in more complex scenarios like multi-tenancy.
قم بتنزيل sample app code from Github here to follow along.
المتطلبات الأساسية
- Basic knowledge of ASP.NET و C#
- Familiarity with إطار عمل الكيانات
- Understanding of حقن التبعية و Interfaces
Project Setup
Begin by creating a واجهة برمجة التطبيقات على الويب project with no authentication. The project we create is going to be very simple and it will only contain one entity called المنتج, with one service called المنتجات والخدمات, and one controller called وحدة التحكم في المنتجات. Its really not even necessary to create a Product Service – we could instead just put all of our business logic in the Products Controller but we will stick to the service pattern and use dependency injection because its good practice. If you are unfamiliar with the service pattern, interfaces, ، أو dependency injection, be sure to read the other tutorials I’ve published on those topics in the blog.
Add Entity Framework
We will begin by adding the necessary Nuget packages for إطار عمل الكيانات. Right click on the project in the solution explorer واختر Manage Nuget Packages. There are three that we need to install:
- Entity Framework Core
- Entity Framework SqlServer
- Entity Framework Tools
Next, create a النماذج folder and create a class called ApplicationDbContext. This class should inherit from the DbContext class which is provided by the Entity Framework Core nuget package. The code should look like this at this point:
عام فئة ApplicationDbContext : DbContext
{
// منشئ — الاصطلاح المستخدم في Entity Framework
عام ApplicationDbContext(خيارات DbContextOptions) : القاعدة(خيارات)
{
}
}في appsettings.json file, create an entry for connection strings and name it default connection like this:
"سلاسل الاتصال": {
"الاتصال الافتراضي": "مصدر البيانات=(localdb)\\mssqllocaldb;Database=queryFilterAppDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},في program.cs add this line to add a database connection as a service to the application:
// إضافة خدمة قاعدة بيانات مع التكوين -- سلسلة الاتصال تُقرأ من ملف appsettings.json
مطور.الخدمات.AddDbContext<ApplicationDbContext> (خيارات => خيارات.UseSqlServer(مطور.الإعدادات.GetConnectionString("الاتصال الافتراضي")));
With those steps out of the way, the application is configured to use a database with Entity Framework. Later we will scaffold an initial migration and create a database called queryFilterAppDb.
Create the Product Entity
في النماذج folder, create one entity named المنتج with the following properties. Make one of the fields a منطقية property called IsDeleted. The Product class should look like this:
عام فئة المنتج
{
عام int المعرّف { احصل على؛; تعيين؛; }
عام سلسلة الاسم { احصل على؛; تعيين؛; }
عام عشري السعر { احصل على؛; تعيين؛; }
عام bool IsDeleted { احصل على؛; تعيين؛; }
}Let’s remember to create a DbSet for our Product entity in the ApplicationDbContext like so:
عام DbSet<المنتج> المنتجات { احصل على; مجموعة; }We will come back to the ApplicationDbContext in a moment for the real fun with query filtering but for now let’s just focus on setting up the application.
Create the Product Service
Create a folder called الخدمات in the top level of the application and within that folder, another folder called المنتجات والخدمات. Here we will create a class called المنتجات والخدمات and an interface called IProductService هكذا:
عام واجهة IProductService
{
IEnumerable<المنتج> GetAllProducts();
المنتج GetProductById(int id);
المنتج إنشاء منتج(طلب إنشاء المنتج (CreateProductRequest));
bool حذف المنتج(int id);
}Above is the واجهة, and below is the الخدمة that contains our business logic for managing Products
عام فئة المنتجات والخدمات : IProductService
{
خاص للقراءة فقط ApplicationDbContext _context; // سياق قاعدة البيانات
عام المنتجات والخدمات(ApplicationDbContext context)
{
_السياق = السياق;
}
// الحصول على قائمة بجميع المنتجات
عام IEnumerable<المنتج> GetAllProducts()
{
var المنتجات = _السياق.المنتجات.ToList();
العودة المنتجات;
}
// استرداد منتج واحد
عام المنتج GetProductById(int id)
{
var المنتج = _السياق.المنتجات.أين(x => x.المعرّف == id).FirstOrDefault();
العودة المنتج;
}
// إنشاء منتج جديد
عام المنتج إنشاء منتج(طلب إنشاء المنتج (CreateProductRequest))
{
var المنتج = جديد المنتج();
المنتج.الاسم = طلب.الاسم;
المنتج.السعر = طلب.السعر;
_السياق.إضافة(المنتج);
_السياق.حفظ التغييرات();
العودة المنتج;
}
// حذف منتج
عام bool حذف المنتج(int id)
{
var المنتج = _السياق.المنتجات.أين(x => x.المعرّف == id).FirstOrDefault();
إذا (المنتج != null)
{
_السياق.إزالة(المنتج);
_السياق.حفظ التغييرات();
العودة صحيح؛;
}
العودة false؛;
}
}For the إنشاء method, create a DTO (data transfer object) class for a new product request. In this case, I’ve named mine طلب إنشاء منتج and placed it into a DTOs folder داخل المنتجات والخدمات folder, like so:
عام فئة طلب إنشاء منتج
{
عام سلسلة الاسم { احصل على؛; تعيين؛; }
عام عشري السعر { احصل على؛; تعيين؛; }
}Next, we will need to register the service in the top-level program.cs class as a transient service. Also in the program.cs we will configure our database to use ApplicationDBContext مع SqlServer and a connection string which is specified in appsettings.json. The program.cs class should look like this when its all finished:
باستخدام مايكروسوفت.EntityFrameworkCore;
باستخدام queryFilterApp.النماذج;
باستخدام queryFilterApp.الخدمات.المنتجات والخدمات;
var مطور = تطبيق ويب.CreateBuilder(args); // <--- 1. إنشاء «المنشئ» (وفقًا لأعراف ASP.NET)
// الخدمات الافتراضية التي تُضاف عند إنشاء قالب 'مشروع واجهة برمجة تطبيقات الويب'
مطور.الخدمات.إضافة وحدات التحكم();
مطور.الخدمات.إضافة نقاط نهاية واجهة برمجة التطبيقات (API)();
// إضافة خدمة قاعدة بيانات مع التكوين -- سلسلة الاتصال تُقرأ من ملف appsettings.json
مطور.الخدمات.AddDbContext<ApplicationDbContext> (خيارات => خيارات.UseSqlServer(مطور.الإعدادات.GetConnectionString("الاتصال الافتراضي")));
// إضافة خدمتنا الخاصة — يجب تسجيل خدمات CRUD بعمر مؤقت
مطور.الخدمات.AddTransient<IProductService, المنتجات والخدمات>();
var تطبيق = مطور.بناء(); // <--- 2. إنشاء التطبيق (وفقًا لمعايير ASP.NET)
// البرمجيات الوسيطة الافتراضية عند اختيار إنشاء 'مشروع واجهة برمجة تطبيقات ويب'
تطبيق.إعادة التوجيه عبر HTTPS();
تطبيق.تفويض الاستخدام();
تطبيق.وحدات التحكم في الخرائط();
تطبيق.تشغيل(); // <--- 3. تشغيل التطبيق (وفقًا لمعايير ASP.NET)Finally, we will create a Products controller with احصل على, منشور, ، و حذف endpoints. The controller will inject an instance of the Product Service as is typically done in ASP.NET applications. Nothing fancy so far!
[الطريق("api/[وحدة التحكم]")]
[ApiController]
عام فئة وحدة التحكم في المنتجات : قاعدة وحدة التحكم
{
خاص للقراءة فقط IProductService _productService;
عام وحدة التحكم في المنتجات(IProductService productService)
{
_productService = المنتج والخدمة; // إدراج خدمة المنتجات
}
// الحصول على قائمة المنتجات
[HttpGet]
عام IActionResult احصل على()
{
var قائمة = _productService.GetAllProducts();
العودة حسنًا(قائمة);
}
// إنشاء منتج جديد
[HttpPost]
عام IActionResult منشور(طلب إنشاء المنتج (CreateProductRequest))
{
var النتيجة = _productService.إنشاء منتج(طلب);
العودة حسنًا(النتيجة);
}
// حذف منتج باستخدام المعرّف
[HttpDelete("{id}")]
عام IActionResult حذف(int id)
{
var النتيجة = _productService.حذف المنتج(id);
العودة حسنًا(النتيجة);
}
}Before we run the application we will need to create an initial migration and run the تحديث قاعدة البيانات command to actually create the database and tables. Note that if you are downloading the sample project on GitHub, the initial migration has already been created, and all you need to do is run the تحديث قاعدة البيانات command in the وحدة التحكم في إدارة الحزم.
تشغيل التطبيق
Now that we have a basic application set up with a database, product service, and controller, run the application.
افتح ساعي البريد or whatever your preferred tool is for testing API endpoints, and let’s start by creating some products.
Create a post request with a CreateProductRequest json object in the body, to send to https://localhost:7237/api/Products
Note that the localhost address in your case may be different if you are not using the GitHub example provided.
This is what the Post request looks like in postman, with الاسم being a سلسلة value and السعر a عشري.

Create a few more products to populate our database, and once you’re done you can test the Get method to get a list a products like so:

If we were to test our last endpoint, the حذف endpoint, we already know what will happen. We could send the delete request with one of the ID numbers and that product would be removed from the database.
What we want to do instead is tell Entity Framework to change the IsDeleted الخاصية إلى صحيح when it receives a delete request for the Product entity. Then we can then change our احصل على request to filter out any products that have a صحيح value in the IsDeleted attribute. With that, we will have implemented a soft delete feature in our application (on Product entities).
The problem is that adding a أين clause to any place we retrieve products would be tedious, and if we ever add more entities to our application, we will need to add the WHERE clause to those queries as well. Instead of that hot mess, we could use a global query filter to apply the clause to every query. Furthermore, we can use the query filter to apply the clause to other entities we add to our application, not just Products.
This is where the fun begins. Let’s start with the first part, intercepting delete requests in Entity Framework and marking the IsDeleted property to true.
Overriding On Save Changes in ApplicationDbContext
As the title suggests, we are going to override the Save Changes method of Entity Framework. Its very common to override the Save Changes method. Overriding just means that you are adding actions that happen during a particular phase of an operation.
في ApplicationDbContext class, add this code block after the DbSet declarations:
عام تجاوز int حفظ التغييرات()
{
foreach (var المدخل في ChangeTracker.المدخلات<المنتج>().ToList())
{
مفتاح (المدخل.الولاية)
{
حالة حالة الكيان.تم الحذف: // intercept delete requests, mark field as deleted
المدخل.الكيان.IsDeleted = صحيح؛;
المدخل.الولاية = حالة الكيان.تم تعديله;
فاصل؛;
}
}
var النتيجة = القاعدة.حفظ التغييرات();
العودة النتيجة;
}With this code in place, entity framework will take a difference course of action with Product entities. We tell EF that for any changes it has in regards to Product entities, check for delete requests (EntityState.Deleted) and for those requests change the IsDeleted property to true. We then send the request along but as EntityState.Modified, so that EF handles the request like an update request.
The foreach loop can be improved further, by looping through entities that implement a particular interface, instead of one specific entity type. For example, if you had Products, Customers, Orders, etc. create an interface type called ISoftDelete, with a mandatory IsDeleted field. Then have all the entities needing soft-delete implement this interface type and in the SaveChanges override, loop through Entries<ISoftDelete>.
Create the Global Query Filter in OnModelCreating
At this point your excitement levels must be through the roof, because you know that the next part is the best part. So without further ado, here is the final piece of the puzzle, the almighty global query filter:
محمي تجاوز فارغ OnModelCreating(أداة ModelBuilder)
{
// filter out deleted entities (soft delete)
مطور.الكيان<المنتج>().HasQueryFilter(s => s.IsDeleted == خطأ);
}Once again we are using the override technique to append actions onto a particular phase of a process, in this case, Entity Framework’s OnModelCreating method. Unlike حفظ التغييرات which fires any time data is persisted to the database, OnModelCreating fires only once, during the application startup.
It is here that we can add a global query filter using the method HasQueryFilter() and then passing a تعبير لامدا as a parameter.
With this query filter in place anytime we retrieve المنتج entities, records that have a value of صحيح من أجل IsDeleted will be omitted. As you can see this is quite powerful and surprisingly simple. Go ahead and make sure its all working by deleting one of the products, and inspecting the database table. If all goes correctly, the record will still be there in the table but its IsDeleted value will be set to صحيح. When you go to retrieve the list of products, the soft-deleted record won’t be returned.
If you add new entity types that also need soft-delete query filters, you can add new lines for them in the OnModelCreating method. Sadly there isn’t a quick and easy way to add the same query filter to all entity types that implement a particular interface like we did in the حفظ التغييرات override.
If you wanted to achieve that functionality you could create an extension method to the ModelBuilder class to handle that, but the code for that is rather advanced. The Nano ASP.NET Boilerplate project utilizes such an extension method for its soft-delete feature as well as audit fields and multi-tenancy.
No matter what level of skill you have as an ASP.NET developer, the نموذج Nano ASP.NET will save you a lot of time building your next application or simply advance your learning if you are trying to understand complex topics.
That concludes this tutorial and I hope you learned something about query filters along the way. To learn more about the Entity Framework, check out this related tutorial on capturing audit data. And if you think you are ready for an advanced topic, dive into my guide to multitenancy in ASP.NET (coming soon).