### Example Usage of Custom QueryString Parameter
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Customization-of-QueryString.md
This example shows how to use the customized querystring parameter in a URL.
```text
/Blogs?category=4
```
--------------------------------
### Query Examples for Nested Object Filtering
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/features/Nested-Relational-Queries.md
Provides example query strings and their corresponding generated LINQ expressions for filtering blogs based on nested author properties like IsPremium and FullName.
```plaintext
| QueryString | Generated LINQ |
| --- | --- |
|`?author.isPremium=True` | `db.Blogs.Where(x => x.Author.IsPremium == true` |
|`?author.isPremium=False&author.fullName=John` | `db.Blogs.Where(x => x.Author.IsPremium == false && x.Author.FullName.Contains("John")`
```
--------------------------------
### Query String Examples for Range Filtering
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Working-with-Range.md
Examples of how to construct query strings for filtering by a range of values. For DateTime ranges, the format may depend on CultureInfo and client-side localization.
```http
/Blogs?Priority.Min=4
```
```http
/Blogs?Priority.Min=3&Priority.Max=5
```
```http
/Blogs?PublishDate.Max=01.05.2019
```
--------------------------------
### Query Examples for Nested Collection Filtering
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/features/Nested-Relational-Queries.md
Provides example query strings and their corresponding generated LINQ expressions for filtering blogs based on nested comment properties like language and message.
```plaintext
| QueryString | Generated LINQ |
| --- | --- |
|`?Comments.Language=en` | `db.Blogs.Where(x => x.Comments.Any(a => a.Language == "en"))` |
| `?comments.language=en&message=awesome` | `db.Blogs.Where(x => x.Message.Contains("awesome") && x.Comments.Any(a => a.Language == "en"))`
```
--------------------------------
### Install AutoFilterer via CLI
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Getting-Started.md
Use this command to add the AutoFilterer NuGet package to your project via the .NET CLI.
```bash
dotnet add package AutoFilterer
```
--------------------------------
### Install AutoFilterer via Package Reference
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Getting-Started.md
Add this XML snippet to your project file to include the AutoFilterer NuGet package.
```xml
```
--------------------------------
### OperatorFilter Usage Examples
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/comparisons/OperatorFilter.md
Demonstrates how to use the OperatorFilter in query strings for filtering data.
```APIDOC
## OperatorFilter Query String Examples
### Description
Examples of how to use the `OperatorFilter` properties in a query string to filter resources.
### Method
GET
### Endpoint
`/books`
### Query Parameters
- **totalPage.gte** (integer) - Optional - Greater than or equal to the specified value.
- **totalPage.lte** (integer) - Optional - Less than or equal to the specified value.
- **totalPage.isNull** (boolean) - Optional - Checks if the value is null.
### Request Example
`/books?totalPage.gte=300`
`/books?totalPage.isNull=true`
`/books?totalPage.gte=120&totalPage.lte=200`
### Response
#### Success Response (200)
Returns a list of books matching the filter criteria.
#### Response Example
```json
[
{
"title": "Sample Book 1",
"totalPage": 350
},
{
"title": "Sample Book 2",
"totalPage": 150
}
]
```
```
--------------------------------
### Filter Blogs by Author Premium Status and Name
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Nested-Relational-Queries.md
Example LINQ query generated for filtering blogs by author's premium status and a partial match on their full name.
```linq
db.Blogs.Where(x => x.Author.IsPremium == false && x.Author.FullName.Contains("John")
```
--------------------------------
### Define Blog Entity Model
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Custom-Expression-for-Property.md
The base entity model used for filtering examples.
```csharp
pulic class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public bool IsPublished { get; set; }
public virtual ICollection Comments { get; set; }
public virtual Author Author { get; set; }
}
```
--------------------------------
### Filter Blogs by Author Premium Status
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Nested-Relational-Queries.md
Example LINQ query generated for filtering blogs where the associated author is a premium member.
```linq
db.Blogs.Where(x => x.Author.IsPremium == true
```
--------------------------------
### Filter Blogs by Comment Language
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Nested-Relational-Queries.md
Example LINQ query generated for filtering blogs where comments match a specific language.
```linq
db.Blogs.Where(x => x.Comments.Any(a => a.Language == "en"))
```
--------------------------------
### Filter Blogs by Comment Language and Message
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Nested-Relational-Queries.md
Example LINQ query generated for filtering blogs by comment language and message content.
```linq
db.Blogs.Where(x => x.Message.Contains("awesome") && x.Comments.Any(a => a.Language == "en"))
```
--------------------------------
### Map Filter Property to Multiple Model Properties
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Property-Name-Mapping.md
Use the [CompareTo] attribute to map a filter property to one or more model properties. This example maps the 'Search' filter property to both 'Title' and 'Author' model properties.
```csharp
public class BookFilter : FilterBase
{
[CompareTo("Title","Author")] // <-- This filter will be applied to Title or Author.
[StringFilterOptions(StringFilterOption.Contains)]
public string Search { get; set; }
}
```
--------------------------------
### Apply PaginationFilterBase to a BookFilter
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Pagination.md
Inherit from PaginationFilterBase to automatically apply query, sorting, and pagination to your filter object. This setup is used in the controller action.
```csharp
public class BookFilter : PaginationFilterBase // <-- Just inherit PaginationFilterBase
{
public string Title { get; set; }
public string Author { get; set; }
public int? Year { get; set; }
// ...
}
```
--------------------------------
### Map Filter Property with Combination Type
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Property-Name-Mapping.md
Define the combination type (AND/OR) between multiple mapped properties using the CombineWith parameter in the [CompareTo] attribute. This example maps the 'Search' filter property to 'Title' and 'Author' with an AND combination.
```csharp
public class BookFilter : FilterBase
{
[CompareTo("Title","Author", CombineWith = CombineType.And)] // <-- 'And'/'Or' can be set from here.
[StringFilterOptions(StringFilterOption.Contains)]
public string Search { get; set; }
}
```
--------------------------------
### Sample Controller with Default AND Combination
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Combine-Parameters-Or-And.md
A C# controller action that applies filtering to a list of blogs using the default AND combination logic. The filter DTO is received from the query string.
```csharp
public class BlogsController : ControllerBase
{
[HttpGet]
public IActionResult Get([FromQuery]BlogFilterDto filter)
{
using(var db = new MyDbContext())
{
// In this case, your expression will be built like that:
// QueryString: /Blogs?priority.min=4&isPublished=false
// x => x.Priority > 4 && x.IsPublished == false
var blogList = db.Blogs.ApplyFilter(filter).ToList();
return Ok(blogList);
}
}
}
```
--------------------------------
### Controller with OR Combination from Query String
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Combine-Parameters-Or-And.md
Shows how to enable OR combination logic by passing 'combineWith=1' in the query string.
```csharp
public class BlogsController : ControllerBase
{
[HttpGet]
public IActionResult Get([FromQuery]BlogFilterDto filter)
{
using(var db = new MyDbContext())
{
// In this case, your expression will be built like that:
// QueryString: /Blogs?priority.min=4&isPublished=false&combineWith=1
// x => x.Priority > 4 || x.IsPublished == false
var blogList = db.Blogs.ApplyFilter(filter).ToList();
return Ok(blogList);
}
}
}
```
--------------------------------
### Querying with OperatorFilter
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/comparisons/OperatorFilter.md
Demonstrates how to use OperatorFilter properties in a querystring for filtering books based on the TotalPage property. Supports various comparison operators and ranges.
```http
/books?totalPage.gte=300
```
```http
/books?totalPage.isNull=true
```
```http
/books?totalPage.gte=120&totalPage.lte=200
```
--------------------------------
### Add AutoFilterer.Swagger Namespace
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Getting-Started.md
Include this using statement in your Startup class to enable AutoFilterer's Swagger integration.
```csharp
using AutoFilterer.Swagger;
```
--------------------------------
### String StartsWith Comparison
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/comparisons/String-Comparisons.md
Use `StringFilterOptions(StringComparison.StartsWith)` to generate a filter that checks if a string begins with a specified value.
```csharp
[StringFilterOptions(StringComparison.StartsWith)]
public string Name { get; set; }
```
--------------------------------
### StringFilterOptions Attribute - Static String Comparisons
Source: https://context7.com/enisn/autofilterer/llms.txt
The StringFilterOptions attribute configures string comparison behavior at design time, supporting exact matches, contains, starts with, ends with, and case-insensitive options.
```APIDOC
## GET /books
### Description
Retrieves a list of books, applying static string comparison filters configured via the StringFilterOptions attribute.
### Method
GET
### Endpoint
/books
### Query Parameters
- **filter.locale** (string) - Optional - Filters books where the locale exactly matches the provided value (case-sensitive by default).
- **filter.description** (string) - Optional - Filters books where the description contains the provided value (case-sensitive by default).
- **filter.title** (string) - Optional - Filters books where the title starts with the provided value (case-sensitive by default).
- **filter.author** (string) - Optional - Filters books where the author contains the provided value, ignoring case.
- **filter.name** (string) - Optional - Filters books where the name contains the provided value, using case-insensitive comparison optimized for databases.
### Request Example
```
GET /books?locale=en-US
GET /books?description=api
GET /books?title=Auto
GET /books?author=john
```
### Response
#### Success Response (200)
- **books** (array) - A list of book objects matching the filter criteria.
#### Response Example
```json
[
{
"title": "Auto Filtering API",
"locale": "en-US",
"description": "An API for auto filtering.",
"author": "John Doe"
}
]
```
```
--------------------------------
### Define Entity Classes for Blog and Author
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/features/Nested-Relational-Queries.md
Defines the structure for Blog and Author entities, including a one-to-one relationship. Used for demonstrating nested filtering over objects.
```csharp
pulic class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public virtual Author Author { get; set; } // We'll work on this field
}
pulic class Author
{
public string AuthorId{ get; set; }
public string BlogId { get; set; }
public DateTime RegisterDate { get; set; }
public string FullName{ get; set; }
public bool IsPremium { get; set; }
public virtual Blog Blog { get; set; }
}
```
--------------------------------
### Apply Nested Filter to Blogs Collection
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/features/Nested-Relational-Queries.md
Demonstrates how to apply a nested filter DTO to a DbSet of Blogs using the ApplyFilter extension method. No explicit includes are required for filtering.
```csharp
pulic ActionResult Index([FromQuery]BlogFilterDto filter)
{
using(var db = new MyDbContext())
{
var data = db.Blogs.ApplyFilter(filter).Tolist();
return View(data)
}
}
```
--------------------------------
### Define Blog and Author Entities
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Nested-Relational-Queries.md
Defines the structure for Blog and Author entities, where Author is a single related object to Blog.
```csharp
pulic class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public virtual Author Author { get; set; } // We'll work on this field
}
pulic class Author
{
public string AuthorId{ get; set; }
public string BlogId { get; set; }
public DateTime RegisterDate { get; set; }
public string FullName{ get; set; }
public bool IsPremium { get; set; }
public virtual Blog Blog { get; set; }
}
```
--------------------------------
### Configure CombineWith Logic
Source: https://context7.com/enisn/autofilterer/llms.txt
Control how multiple filter conditions are combined using either AND or OR logic.
```csharp
public class BlogFilter : FilterBase
{
public int? CategoryId { get; set; }
public Range Priority { get; set; }
public bool? IsPublished { get; set; }
}
[HttpGet]
public IActionResult GetBlogs([FromQuery] BlogFilter filter)
{
// Option 1: Set in code
filter.CombineWith = CombineType.Or;
var blogs = db.Blogs.ApplyFilter(filter).ToList();
return Ok(blogs);
}
// Option 2: Set from query string
// GET /blogs?priority.min=4&isPublished=false&combineWith=0
// Result: x => x.Priority > 4 && x.IsPublished == false (AND)
// GET /blogs?priority.min=4&isPublished=false&combineWith=1
// Result: x => x.Priority > 4 || x.IsPublished == false (OR)
```
--------------------------------
### Controller Action Using Autofilterer
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Pagination.md
This controller action demonstrates how to use the ApplyFilter method with a custom filter object that inherits from PaginationFilterBase. The result is a paginated and filtered list of books.
```csharp
[HttpGet]
public IActionResult Get([FromQuery]BookFilter filter)
{
var result = db.Books.ApplyFilter(filter).ToList();
return Ok(result);
}
```
--------------------------------
### Define Blog Entity
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Basics.md
Represents the data model for the Blog entity.
```csharp
public class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public int Priority { get; set; }
public bool IsPublished { get; set; }
public DateTime PublishDate { get; set; }
}
```
--------------------------------
### Define a BookFilter Class
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Filtering.md
Create a filter object by inheriting from FilterBase and defining properties for each field you want to filter. Ensure ValueTypes are nullable to handle cases where values are not provided.
```csharp
public class BookFilter : FilterBase // ← Inherit from FilterBase
{
public string Title { get; set; }
public int? Year { get; set; } // ← Value Types have to be nullable
// ...
// Only written properties can be filterable
}
```
--------------------------------
### Define a BookFilter class
Source: https://github.com/enisn/autofilterer/wiki/Migration-to-v2.1
Configure default sorting and filter properties within the filter class definition.
```csharp
public class BookFilter : PaginationFilterBase
{
public BookFilter()
{
// Set the default values in ctor or you can override them.
Sort = nameof(Book.Year);
SortBy = Sorting.Descending;
}
public StringFilter Title { get; set; }
[StringFilterOptions(StringFilterOption.Contains)]
public string Language { get; set; }
public StringFilter Author { get; set; }
public OperatorFilter TotalPage { get; set; }
public OperatorFilter Year { get; set; }
}
```
--------------------------------
### Configure Swagger Generation
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/AutoFilterer-Swagger.md
Register the AutoFilterer parameter support within the AddSwaggerGen configuration block in your Startup.
```csharp
services.AddSwaggerGen(c =>
{
c.UseAutoFiltererParameters(); // <-- Add this here.
// ...
});
```
--------------------------------
### Implement Controller Filtering
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Basics.md
Demonstrates applying the filter DTO to a database query within an ASP.NET Core controller action.
```csharp
public class BlogsController : ControllerBase
{
[HttpGet]
public IActionResult Get([FromQuery]BlogFilterDto filter)
{
using(var db = new MyDbContext())
{
var blogList = db.Blogs.ApplyFilter(filter).ToList();
return Ok(blogList);
}
}
}
```
--------------------------------
### Implement CompareTo Attribute
Source: https://context7.com/enisn/autofilterer/llms.txt
Map a single filter property to multiple entity properties to implement cross-field search functionality.
```csharp
public class BookFilter : FilterBase
{
// Search in both Title and Author properties with OR logic
[CompareTo("Title", "Author")]
[StringFilterOptions(StringFilterOption.Contains)]
public string Search { get; set; }
// Search with AND logic
[CompareTo("Title", "Description", CombineWith = CombineType.And)]
[StringFilterOptions(StringFilterOption.Contains)]
public string ExactSearch { get; set; }
}
[HttpGet]
public IActionResult GetBooks([FromQuery] BookFilter filter)
{
var books = db.Books.ApplyFilter(filter).ToList();
return Ok(books);
}
// Generated LINQ for search=Potter:
// x => x.Title.Contains("Potter") || x.Author.Contains("Potter")
// Generated LINQ for exactSearch=magic:
// x => x.Title.Contains("magic") && x.Description.Contains("magic")
```
--------------------------------
### Define Blog and Comment Entities
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Nested-Relational-Queries.md
Defines the structure for Blog and Comment entities, where Comments is a collection related to Blog.
```csharp
pulic class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public virtual ICollection Comments { get; set; } // We'll work on this field
}
pulic class Comment
{
public string CommentId { get; set; }
public string BlogId { get; set; }
public string Language { get; set; }
public string Message { get; set; }
public virtual Blog Blog { get; set; }
}
```
--------------------------------
### Create DTOs for Filtering Authors
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Nested-Relational-Queries.md
Creates DTOs for filtering Blog entities based on Author properties like IsPremium and FullName. Ensure the nested DTO name matches the entity navigation property.
```csharp
pulic class BlogFilterDto : FilterBase
{
public int? CategoryId { get; set; }
public string Title { get; set; }
public AuthorFilterDto Comments { get; set; } // Be careful, it's not a collection and same name with entity.
}
pulic class AuthorFilterDto : FilterBase
{
public bool? IsPremium { get; set; }
[StringFilterOptions(StringFilterOption.Contains)]
public string FullName { get; set; }
}
```
--------------------------------
### Configure SwaggerGen with AutoFilterer Parameters
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Getting-Started.md
Call `UseAutoFiltererParameters()` within your `AddSwaggerGen` configuration to integrate AutoFilterer's filtering capabilities with Swagger documentation.
```csharp
services.AddSwaggerGen(c =>
{
c.UseAutoFiltererParameters(); // <-- Add this here.
// ...
});
```
--------------------------------
### Pagination and Sorting with PaginationFilterBase
Source: https://context7.com/enisn/autofilterer/llms.txt
Use PaginationFilterBase for filters that require both pagination and sorting. The ApplyFilter method automatically handles filtering, sorting, and pagination. Default values are page=1 and perPage=10.
```csharp
// Filter with pagination - inherits from PaginationFilterBase
public class BookFilter : PaginationFilterBase
{
public string Title { get; set; }
public string Author { get; set; }
public int? Year { get; set; }
}
// Controller usage
[HttpGet]
public IActionResult GetBooks([FromQuery] BookFilter filter)
{
// Applies filter, sorting, and pagination automatically
var result = db.Books.ApplyFilter(filter).ToList();
return Ok(result);
}
// Pagination parameters (defaults: page=1, perPage=10):
// GET /books?page=2
// GET /books?perPage=16
// GET /books?page=2&perPage=16
// Sorting parameters:
// GET /books?sort=Title
// GET /books?sort=Title&sortBy=Ascending
// GET /books?sort=Year&sortBy=Descending
// Combined:
// GET /books?page=1&perPage=20&sort=Year&sortBy=Descending&isPublished=true
```
--------------------------------
### Apply Filter using ApplyFilter Extension Method
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Filtering.md
Utilize the ApplyFilter extension method directly on an IQueryable type for a more concise way to apply filter objects.
```csharp
public IActionResult GetBooks([FromQuery]BookFilter filter)
{
return Ok(db.Books.ApplyFilter(filter).ToList());
}
```
--------------------------------
### Define Entity Classes for Blog and Comment
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/features/Nested-Relational-Queries.md
Defines the structure for Blog and Comment entities, including a one-to-many relationship. Used for demonstrating nested filtering over collections.
```csharp
pulic class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public virtual ICollection Comments { get; set; } // We'll work on this field
}
pulic class Comment
{
public string CommentId { get; set; }
public string BlogId { get; set; }
public string Language { get; set; }
public string Message { get; set; }
public virtual Blog Blog { get; set; }
}
```
--------------------------------
### Handle Controller Request
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/OperatorFilter.md
Bind the filter model from query parameters in an ASP.NET Core controller action.
```csharp
[HttpGet]
public IActionResult Get([FromQuery]BookFilter filter)
{
var result = db.Books.ApplyFilter(filter).ToList();
return Ok();
}
```
--------------------------------
### Define a Book Filter with Sorting
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Sorting.md
Create a filter class by inheriting from OrderableFilterBase to enable sorting. Add properties for filtering criteria such as Title, Author, and Year.
```csharp
public class BookFilter : OrderableFilterBase // <-- Just inherit OrderableFilterBase
{
public string Title { get; set; }
public string Author { get; set; }
public int? Year { get; set; }
// ...
}
```
--------------------------------
### Define Blog entity model
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/String-Comparisons.md
The base entity class containing the string field to be filtered.
```csharp
public class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; } // <-- We'll work on this string field
public int Priority { get; set; }
public bool IsPublished { get; set; }
public DateTime PublishDate { get; set; }
}
```
--------------------------------
### StringFilterOptions for Static String Comparisons
Source: https://context7.com/enisn/autofilterer/llms.txt
Configure string comparison behavior at design time using the StringFilterOptions attribute. Supports Equals, StartsWith, EndsWith, and Contains with optional case sensitivity.
```csharp
public class BookFilter : FilterBase
{
// Default: exact match
[StringFilterOptions(StringFilterOption.Equals)]
public string Locale { get; set; }
// Contains search
[StringFilterOptions(StringFilterOption.Contains)]
public string Description { get; set; }
// Starts with search
[StringFilterOptions(StringFilterOption.StartsWith)]
public string Title { get; set; }
// Case-insensitive contains
[StringFilterOptions(StringFilterOption.Contains, StringComparison.InvariantCultureIgnoreCase)]
public string Author { get; set; }
}
// For better database compatibility (MongoDB, SQL Server), use ToLowerContainsComparison
public class BookFilterCompatible : FilterBase
{
// Generates: x => x.Name.ToLower().Contains(value.ToLower())
[ToLowerContainsComparison]
public string Name { get; set; }
}
[HttpGet]
public IActionResult GetBooks([FromQuery] BookFilter filter)
{
var books = db.Books.ApplyFilter(filter).ToList();
return Ok(books);
}
```
--------------------------------
### Define the Blog Entity
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Working-with-Range.md
The base entity model used for filtering operations.
```csharp
public class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public int Priority { get; set; }
public bool IsPublished { get; set; }
public DateTime PublishDate { get; set; }
}
```
--------------------------------
### Apply Sorting Filter to Books
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Sorting.md
Use this controller action to apply a filter with sorting to a collection of books. Ensure your BookFilter class inherits from OrderableFilterBase.
```csharp
using Microsoft.AspNetCore.Mvc;
// ... other usings
[HttpGet]
public IActionResult Get([FromQuery]BookFilter filter)
{
var result = db.Books.ApplyFilter(filter).ToList();
return Ok(result);
}
```
--------------------------------
### Add AutoFilterer Parameters to Swagger
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Set-Up.md
Integrate AutoFilterer with Swagger by adding the `UseAutoFiltererParameters()` method within your SwaggerGen configuration in the Startup class. This requires the `AutoFilterer.Swagger` NuGet package.
```csharp
using AutoFilterer.Swagger;
// ...
services.AddSwaggerGen(c =>
{
c.UseAutoFiltererParameters(); // <-- Add this here.
// ...
});
```
--------------------------------
### StringFilter - Dynamic String Comparisons
Source: https://context7.com/enisn/autofilterer/llms.txt
StringFilter allows clients to specify string comparison types at runtime, supporting equality, containment, prefix, suffix, and null checks.
```APIDOC
## GET /books
### Description
Retrieves a list of books, applying dynamic string filters to the title and author properties.
### Method
GET
### Endpoint
/books
### Query Parameters
- **filter.title.eq** (string) - Optional - Filters books where the title exactly matches the provided string.
- **filter.title.not** (string) - Optional - Filters books where the title does not exactly match the provided string.
- **filter.title.contains** (string) - Optional - Filters books where the title contains the provided string.
- **filter.title.notContains** (string) - Optional - Filters books where the title does not contain the provided string.
- **filter.title.startsWith** (string) - Optional - Filters books where the title starts with the provided string.
- **filter.title.notStartsWith** (string) - Optional - Filters books where the title does not start with the provided string.
- **filter.title.endsWith** (string) - Optional - Filters books where the title ends with the provided string.
- **filter.title.notEndsWith** (string) - Optional - Filters books where the title does not end with the provided string.
- **filter.title.isNull** (boolean) - Optional - Filters books where the title is null.
- **filter.title.isNotNull** (boolean) - Optional - Filters books where the title is not null.
- **filter.title.isEmpty** (boolean) - Optional - Filters books where the title is empty (null or "").
- **filter.title.isNotEmpty** (boolean) - Optional - Filters books where the title is not empty.
- **filter.author.eq** (string) - Optional - Filters books where the author exactly matches the provided string.
- **filter.author.not** (string) - Optional - Filters books where the author does not exactly match the provided string.
- **filter.author.contains** (string) - Optional - Filters books where the author contains the provided string.
- **filter.author.notContains** (string) - Optional - Filters books where the author does not contain the provided string.
- **filter.author.startsWith** (string) - Optional - Filters books where the author starts with the provided string.
- **filter.author.notStartsWith** (string) - Optional - Filters books where the author does not start with the provided string.
- **filter.author.endsWith** (string) - Optional - Filters books where the author ends with the provided string.
- **filter.author.notEndsWith** (string) - Optional - Filters books where the author does not end with the provided string.
- **filter.author.isNull** (boolean) - Optional - Filters books where the author is null.
- **filter.author.isNotNull** (boolean) - Optional - Filters books where the author is not null.
- **filter.author.isEmpty** (boolean) - Optional - Filters books where the author is empty (null or "").
- **filter.author.isNotEmpty** (boolean) - Optional - Filters books where the author is not empty.
### Request Example
```
GET /books?title.eq=Harry Potter
GET /books?title.contains=Potter
GET /books?title.startsWith=Harry
GET /books?author.isEmpty=false
GET /books?title.isNotNull=true
```
### Response
#### Success Response (200)
- **books** (array) - A list of book objects matching the filter criteria.
#### Response Example
```json
[
{
"title": "Harry Potter and the Sorcerer's Stone",
"author": "J.K. Rowling"
}
]
```
```
--------------------------------
### Range for Min/Max Range Queries
Source: https://context7.com/enisn/autofilterer/llms.txt
Utilize Range for range filtering on numeric and DateTime properties. Define boundaries using Min and Max properties for precise queries.
```csharp
public class Blog
{
public string BlogId { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public int Priority { get; set; }
public bool IsPublished { get; set; }
public DateTime PublishDate { get; set; }
}
public class BlogFilter : FilterBase
{
public int? CategoryId { get; set; }
public string Title { get; set; }
public bool? IsPublished { get; set; }
// Range for numeric properties - do NOT use nullable types
public Range Priority { get; set; }
// Range for DateTime properties
public Range PublishDate { get; set; }
}
[HttpGet]
public IActionResult GetBlogs([FromQuery] BlogFilter filter)
{
var blogs = db.Blogs.ApplyFilter(filter).ToList();
return Ok(blogs);
}
```
--------------------------------
### Create Blog Filter DTO
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/Basics.md
Defines a filter DTO that inherits from FilterBase to enable filtering on specific properties.
```csharp
public class BlogFilterDto : FilterBase
{
public int CategoryId { get; set; }
public int Priority { get; set; }
public bool? IsPublished { get; set; }
}
```
--------------------------------
### StringFilter Usage
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/comparisons/StringFilter.md
Defines how to use StringFilter within a filter object and how to apply it via query strings.
```APIDOC
## StringFilter Properties
### Description
The StringFilter type provides various operators for dynamic string comparison in filter objects.
### Properties
- **Eq** (string) - Optional - Parameter for == operator.
- **Not** (string) - Optional - Parameter for != operator.
- **Equals** (string) - Optional - Parameter for String.Equals.
- **Contains** (string) - Optional - Parameter for String.Contains.
- **NotContains** (string) - Optional - Parameter for !String.Contains.
- **StartsWith** (string) - Optional - Parameter for String.StartsWith.
- **NotStartsWith** (string) - Optional - Parameter for !String.StartsWith.
- **EndsWith** (string) - Optional - Parameter for String.EndsWith.
- **NotEndsWith** (string) - Optional - Parameter for !String.EndsWith.
- **IsNull** (boolean) - Optional - Parameter for == null.
- **IsNotNull** (boolean) - Optional - Parameter for != null.
- **IsEmpty** (boolean) - Optional - Parameter for String.IsNullOrEmpty.
- **IsNotEmpty** (boolean) - Optional - Parameter for !String.IsNullOrEmpty.
### Usage Example
```csharp
public class BookFilter : FilterBase
{
public StringFilter Title { get; set; }
}
```
### Query String Examples
- `yourdomain.com/books?title.eq=Harry Potter`
- `yourdomain.com/books?title.isEmpty=true`
```
--------------------------------
### Override Pagination Parameter Names
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Customizing-Pagination-Parameters.md
Customize query string parameter names for pagination by decorating properties with [FromQuery(Name = "...")]. This allows using different names like 'p' for page and 'limit' for perPage.
```csharp
public class BlogFilterDto : PaginationFilterBase
{
public int? CategoryId { get; set; }
public Range Priority { get; set; }
public string Title { get; set; }
public bool? IsPublished { get; set; }
public Range PublishDate { get; set; }
[FromQuery(Name = "p")] // <-- you can set querystring name
public override int Page { get => base.Page; set => base.Page = value; }
[FromQuery(Name = "limit")]
public override int PerPage { get => base.PerPage; set => base.PerPage = value; }
}
```
--------------------------------
### Integrate AutoFilterer with Swagger
Source: https://context7.com/enisn/autofilterer/llms.txt
Use the AutoFilterer.Swagger package to enhance Swagger documentation. This integration displays filter parameters as dropdowns and properly documents complex filter types like Enum, Range, and StringFilter.
```bash
dotnet add package AutoFilterer.Swagger
```
```csharp
// Startup.cs or Program.cs
using AutoFilterer.Swagger;
services.AddSwaggerGen(c =>
{
c.UseAutoFiltererParameters(); // Enable AutoFilterer parameter descriptions
// Other swagger configuration...
});
// After setup, Swagger UI shows:
// - Enum properties as dropdowns
// - Range as min/max fields
// - StringFilter/OperatorFilter with all available sub-properties
// - Proper documentation for all filter types
```
--------------------------------
### Implement OperatorComparison Attribute
Source: https://context7.com/enisn/autofilterer/llms.txt
Use OperatorComparison to generate direct operator queries instead of method calls, which is essential for providers like MongoDB.
```csharp
public class BookFilter : PaginationFilterBase
{
// Generates: x => x.Title == value
[OperatorComparison(OperatorType.Equal)]
public string Title { get; set; }
// Generates: x => x.Year >= value
[OperatorComparison(OperatorType.GreaterThanOrEqual)]
public int? Year { get; set; }
// Generates: x => x.Price < value
[OperatorComparison(OperatorType.LessThan)]
public decimal? MaxPrice { get; set; }
}
[HttpGet]
public IActionResult GetBooks([FromQuery] BookFilter filter)
{
// Works with MongoDB and other providers that don't support method calls
var books = db.Books.ApplyFilter(filter).ToList();
return Ok(books);
}
// Available OperatorTypes:
// - Equal (==)
// - NotEqual (!=)
// - GreaterThan (>)
// - LessThan (<)
// - GreaterThanOrEqual (>=)
// - LessThanOrEqual (<=)
```
--------------------------------
### Define a Filter Model
Source: https://github.com/enisn/autofilterer/blob/develop/README.md
Create a filter class inheriting from PaginationFilterBase with properties matching entity fields, using attributes for specific comparison logic.
```csharp
public class ProductFilter : PaginationFilterBase
{
public Range Price { get; set; }
[ToLowerContainsComparison]
public string Name { get; set; }
[StringFilteringOptions(StringFilterOption.Equals)]
public string Locale { get; set; }
}
```
--------------------------------
### Controller with OR Combination Set in Code
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Combine-Parameters-Or-And.md
Demonstrates how to set the CombineWith property to 'Or' directly in the controller code to change the filtering logic.
```csharp
public class BlogsController : ControllerBase
{
[HttpGet]
public IActionResult Get([FromQuery]BlogFilterDto filter)
{
using(var db = new MyDbContext())
{
filter.CombineWith = CombineType.Or; // <-- Can be defined here
// In this case, your expression will be built like that:
// QueryString: /Blogs?priority.min=4&isPublished=false
// x => x.Priority > 4 || x.IsPublished == false
var blogList = db.Blogs.ApplyFilter(filter).ToList();
return Ok(blogList);
}
}
}
```
--------------------------------
### Apply OperatorComparison Attribute for Direct Comparison
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/comparisons/Operator-Comparisons.md
Use the [OperatorComparison] attribute with an OperatorType to ensure direct operator comparisons in generated queries. This is useful for providers that do not support default methods like Equals() with StringComparison, such as MongoDB.
```csharp
public class MyFilter : PaginationFilterBase
{
[OperatorComparison(OperatorType.Equal)] // <-- This generates query with operator
public string Title { get; set; } // something like that: x => x.Title == "something"
}
```
--------------------------------
### Define Blog Filter DTO
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Combine-Parameters-Or-And.md
A C# DTO for filtering blog posts, inheriting from FilterBase and including specific filterable properties.
```csharp
public class BlogFilterDto : FilterBase
{
public int CategoryId { get; set; }
public Range Priority { get; set; }
public bool? IsPublished { get; set; }
}
```
--------------------------------
### Basic Filtering with FilterBase
Source: https://context7.com/enisn/autofilterer/llms.txt
Define a filter DTO inheriting from FilterBase and use the ApplyFilter extension method in a controller to automatically generate LINQ expressions. Ensure property names match entity properties and value types are nullable.
```csharp
// Entity definition
public class Book
{
public string Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public int Year { get; set; }
public int TotalPage { get; set; }
public bool IsPublished { get; set; }
}
// Filter DTO - inherits from FilterBase
public class BookFilter : FilterBase
{
public string Title { get; set; }
public string Author { get; set; }
public int? Year { get; set; } // Value types must be nullable
public bool? IsPublished { get; set; }
}
// Controller usage
[HttpGet]
public IActionResult GetBooks([FromQuery] BookFilter filter)
{
// ApplyFilter extension method generates LINQ expression automatically
var books = db.Books.ApplyFilter(filter).ToList();
return Ok(books);
}
// Alternative: use ApplyFilterTo method on filter object
[HttpGet]
public IActionResult GetBooksAlt([FromQuery] BookFilter filter)
{
var query = filter.ApplyFilterTo(db.Books);
return Ok(query.ToList());
}
// Sample requests:
// GET /books?title=Middlemarch
// GET /books?title=Nostromo&year=1904
// GET /books?isPublished=true&year=2020
```
--------------------------------
### Apply Filter to Query
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/OperatorFilter.md
Use the ApplyFilter method on your database context to process the filter model.
```csharp
public IList GetBooks(BookFilter filter)
{
return db.Books.ApplyFilter(filter).ToList();
}
```
--------------------------------
### String Equals Comparison
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/comparisons/String-Comparisons.md
Use `StringFilterOptions(StringComparison.Equals)` to generate a filter that checks for exact string equality. This is the default comparison type.
```csharp
[StringFilterOptions(StringComparison.Equals)]
public string Name { get; set; }
```
--------------------------------
### Create DTOs for Filtering Blog and Author
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/features/Nested-Relational-Queries.md
Creates DTOs that inherit from FilterBase to define filtering criteria for Blog and Author entities. The Author property in BlogFilterDto is used for nested object filtering.
```csharp
pulic class BlogFilterDto : FilterBase
{
public int? CategoryId { get; set; }
public string Title { get; set; }
public AuthorFilterDto Comments { get; set; } // Be careful, it's not a collection and same name with entity.
}
pulic class AuthorFilterDto : FilterBase
{
public bool? IsPremium { get; set; }
[StringFilterOptions(StringFilterOption.Contains)]
public string FullName { get; set; }
}
```
--------------------------------
### Define Filter Model
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Filtering.md
Create a filter class by inheriting from FilterBase. Value types must be nullable to be filterable.
```csharp
public class BookFilter : FilterBase // <-- Just inherit FilterBase
{
public string Title { get; set; }
public string Author { get; set; }
public int? Year { get; set; } // <-- ValueTypes must be nullable
// ...
// Only written properties can be filterable
}
```
--------------------------------
### Apply Filter to Database Query
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Pagination.md
Use the ApplyFilter method to integrate filtering, sorting, and pagination into your database queries. This method is available after inheriting from PaginationFilterBase.
```csharp
var result = db.Books.ApplyFilter(filter).ToList();
return Ok(result);
```
--------------------------------
### Create DTOs for Filtering Comments
Source: https://github.com/enisn/autofilterer/blob/develop/sandbox/WebApplication.API/Docs/Nested-Relational-Queries.md
Creates DTOs for filtering Blog entities based on Comment properties like Language and Message. Ensure the nested DTO name matches the entity navigation property.
```csharp
pulic class BlogFilterDto : FilterBase
{
public int? CategoryId { get; set; }
public string Title { get; set; }
public CommentFilterDto Comments { get; set; } // Be careful, it's not a collection and same name with entity.
}
pulic class CommentFilterDto : FilterBase
{
public string Language { get; set; }
[StringFilterOptions(StringFilterOption.Contains)]
public string Message { get; set; }
}
```
--------------------------------
### Define a Basic Filter Class
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/comparisons/Operator-Comparisons.md
Define a filter class that inherits from PaginationFilterBase. This is a prerequisite for applying AutoFilterer attributes.
```csharp
public class MyFilter : PaginationFilterBase
{
public string Title { get; set; }
}
```
--------------------------------
### Define BookFilter with OperatorFilter
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/comparisons/OperatorFilter.md
Defines a BookFilter class inheriting from FilterBase, using OperatorFilter for the TotalPage property to enable dynamic comparison of integer values.
```csharp
public class BookFilter : FilterBase
{
public OperatorFilter TotalPage { get; set; }
}
```
--------------------------------
### Sorting Only with OrderableFilterBase
Source: https://context7.com/enisn/autofilterer/llms.txt
Utilize OrderableFilterBase when only sorting is required, allowing separate handling of pagination. The ApplyFilter method applies sorting automatically.
```csharp
// Filter with sorting only
public class BookFilter : OrderableFilterBase
{
public string Title { get; set; }
public string Author { get; set; }
public int? Year { get; set; }
}
[HttpGet]
public IActionResult GetBooks([FromQuery] BookFilter filter)
{
var result = db.Books.ApplyFilter(filter).ToList();
return Ok(result);
}
// Sorting requests:
// GET /books?sort=Title
// GET /books?sort=Title&sortBy=Ascending
// GET /books?sort=Author&sortBy=Descending
```
--------------------------------
### Apply Filter in Controller
Source: https://github.com/enisn/autofilterer/blob/develop/README.md
Use the ApplyFilter extension method on an IQueryable to transform the filter model into LINQ expressions.
```csharp
public IActionResult GetProducts([FromQuery]ProductFilter filter)
{
var products = db.Products.ApplyFilter(filter).ToList();
return Ok(products);
}
```
--------------------------------
### Extending Generated Filter with Inheritance
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/generators/AutoFilterer-Generators.md
Alternatively, you can create a new class that inherits from the auto-generated filter class. This allows you to override properties, such as those related to pagination, and apply attributes like [FromQuery] for custom binding.
```csharp
public class AdvancedBookFilter : BookFilter
{
[FromQuery(Name = "p")]
public override int Page { get; set; }
[FromQuery(Name = "size")]
public override int PerPage { get; set; }
}
```
--------------------------------
### Create DTOs for Filtering Blog and Comment
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/features/Nested-Relational-Queries.md
Creates DTOs that inherit from FilterBase to define filtering criteria for Blog and Comment entities. The Comments property in BlogFilterDto is crucial for nested collection filtering.
```csharp
pulic class BlogFilterDto : FilterBase
{
public int? CategoryId { get; set; }
public string Title { get; set; }
public CommentFilterDto Comments { get; set; } // Be careful, it's not a collection and same name with entity.
}
pulic class CommentFilterDto : FilterBase
{
public string Language { get; set; }
[StringFilterOptions(StringFilterOption.Contains)]
public string Message { get; set; }
}
```
--------------------------------
### Implement Array-based Filter
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/features/Array-Search.md
Uses an array property in the filter class to enable multi-selectable filtering.
```csharp
public class BookFilter : PaginationFilterBase
{
public PublishStatus[] Status { get; set; } // <-- Make this array, see the magic!
}
```
--------------------------------
### Create Filtering DTO
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Custom-Expression-for-Property.md
Define a DTO inheriting from FilterBase to handle query parameters.
```csharp
public class SearchDto : FilterBase
{
[FromQuery(Name = "q")]
public string Search { get; set; }
```
--------------------------------
### Override OperatorFilter parameters for backward compatibility
Source: https://github.com/enisn/autofilterer/wiki/Migration-to-v2
Use this class to map old 'Min' and 'Max' query parameters to the new 'Gte' and 'Lte' properties in OperatorFilter.
```csharp
public class CustomRange : OperatorFilter
where T : struct
{
[FromQuery("Min")]
public override T Gte { get; set; }
[FromQuery("Max")]
public override T Lte { get; set; }
}
```
--------------------------------
### Implement Custom Filtering Attribute
Source: https://github.com/enisn/autofilterer/blob/develop/docs/en/examples/Custom-Expression-for-Property.md
Create a custom attribute by inheriting from FilteringOptionsBaseAttribute and overriding BuildExpression.
```csharp
public class BlogSearchAttribute : FilteringOptionsBaseAttribute
{
public override Expression BuildExpression(Expression expressionBody, PropertyInfo targetProperty, PropertyInfo filterProperty, object value)
{
// Also means: x => x.Title == "someValue" || x.Content == "someValue"
return Expression.Or(
Expression.Equal(
Expression.Property(expressionBody, "Title"),
Expression.Constant(value)
),
Expression.Equal(
Expression.Property(expressionBody, "Content"),
Expression.Constant(value)
)
);
}
}
```
--------------------------------
### Auto-Generate Filter DTOs with Source Generators
Source: https://context7.com/enisn/autofilterer/llms.txt
Use the AutoFilterer.Generators package to automatically create filter objects from entity classes. Add the [GenerateAutoFilter] attribute to your entity class. Generated filters map numeric properties to Range and add appropriate string comparison attributes.
```bash
dotnet add package AutoFilterer.Generators
```
```csharp
// Add [GenerateAutoFilter] attribute to entity
[GenerateAutoFilter]
public class Book
{
public string Title { get; set; }
public int? Year { get; set; }
public int TotalPage { get; set; }
public DateTime PublishTime { get; set; }
}
// Use directly in controller
[HttpGet]
public List GetBooks([FromQuery] BookFilter filter)
{
return db.Books.ApplyFilter(filter).ToList();
}
// Custom namespace
[GenerateAutoFilter("My.Custom.Namespace.Filters")]
public class Author
{
public string Name { get; set; }
public int Age { get; set; }
}
// Extend generated filter with partial class
namespace My.Custom.Namespace.Filters
{
public partial class AuthorFilter
{
public string ExtraParameter { get; set; }
public AuthorFilter()
{
SortBy = Sorting.Descending;
PerPage = 36;
}
}
}
// Or extend via inheritance
public class AdvancedBookFilter : BookFilter
{
[FromQuery(Name = "p")]
public override int Page { get; set; }
[FromQuery(Name = "size")]
public override int PerPage { get; set; }
}
```