Sam.DynamicPredicate
1.0.0
See the version list below for details.
dotnet add package Sam.DynamicPredicate --version 1.0.0
NuGet\Install-Package Sam.DynamicPredicate -Version 1.0.0
<PackageReference Include="Sam.DynamicPredicate" Version="1.0.0" />
paket add Sam.DynamicPredicate --version 1.0.0
#r "nuget: Sam.DynamicPredicate, 1.0.0"
// Install Sam.DynamicPredicate as a Cake Addin #addin nuget:?package=Sam.DynamicPredicate&version=1.0.0 // Install Sam.DynamicPredicate as a Cake Tool #tool nuget:?package=Sam.DynamicPredicate&version=1.0.0
Dynamic Filtering
In software development, one of the critical needs is filtering data based on various and dynamic conditions. The Sam.DynamicPredicate package provides developers with a powerful tool for this purpose. This article explores the Sam.DynamicPredicate package, how to use it, and the benefits it offers for filtering data using LINQ.
Introduction to the Sam.DynamicPredicate Package
The Sam.DynamicPredicate package allows you to create LINQ queries dynamically based on predicate strings. By leveraging .NET's Reflection and Expression Trees, this package converts filter conditions into executable LINQ expressions.
How to Use the Sam.DynamicPredicate Package
To use this package, You should install Sam.DynamicPredicate with NuGet using the following command
Install-Package Sam.DynamicPredicate
Or via the .NET Core command line interface:
dotnet add package Sam.DynamicPredicate
Example Usage in an ASP.NET Core Controller
After installing the package, you can use it to dynamically build LINQ queries based on string predicates. Below is an example within an ASP.NET Core controller (ProductController):
[ApiController]
[Route("api/[controller]/[action]")]
public class ProductController(ApplicationDbContext applicationDbContext, ILogger<Product> logger) : ControllerBase
{
[HttpGet]
public async Task<object> Get()
{
var query = applicationDbContext.Products.AsQueryable();
query = query.Where("Id == 1 || Id == 2 || ( Name StartsWith Pro && Price >= 10000 )");
var sqlQuery = query.ToQueryString();
logger.LogInformation("query -> " + sqlQuery);
return new
{
SqlQuery = sqlQuery,
Data= await query.ToListAsync()
};
}
}
Explanation
- Install Package: Use dotnet add package command to add Sam.DynamicPredicate to your project dependencies.
- Controller Setup: ProductController is set up as an ASP.NET Core controller handling HTTP GET requests.
- Query Building: Inside the Get() method, _context.Products.AsQueryable() initializes a queryable collection of products from your database.
- Dynamic Query: query.Where("Id == 1 || Id == 2 || (Name.StartsWith("Pro") && Price >= 10000)") demonstrates the use of Sam.DynamicPredicate. This method dynamically constructs a LINQ query based on the provided string predicate.
- Logging: query.ToQueryString() converts the LINQ query to a SQL string, logged using _logger.LogInformation().
- Return: The method returns an anonymous object containing the SQL query (SqlQuery) and the asynchronously fetched data (Data) converted to JSON.
The value of the sqlQuery variable in this example is as follows
SELECT [p].[Id], [p].[BarCode], [p].[Name], [p].[Price]
FROM [Products] AS [p]
WHERE [p].[Id] IN (CAST(1 AS bigint), CAST(2 AS bigint)) OR ([p].[Name] LIKE N'Pro%' AND [p].[Price] >= 10000.0E0)
Note that the where method, which has a string input, is located in the Sam.DynamicPredicate namespace.
A guide to making string filters
Benefits of Using the Sam.DynamicPredicate Package
Dynamic and Adjustable Filters
- One of the biggest advantages of this package is the ability to define dynamic filters based on changing needs. You can input various conditions as strings and easily apply the filters.
Reduced Code Complexity
- Using this package, your code becomes cleaner and more manageable. There is no need to write complex queries for every condition, and you can use a uniform structure for all conditions.
Improved Readability and Maintenance
- Utilizing predicate strings instead of combining multiple LINQ expressions enhances code readability. This approach simplifies maintenance and makes it easy to modify filter conditions.
High Flexibility
- The Sam.DynamicPredicate package supports various types of conditions, including simple comparisons, text comparisons, and more complex conditions using logical operators.
High Performance
- With this package, the generated queries are optimized and directly translated into equivalent SQL statements, ensuring high performance during execution.
Open Source Project Availability
The Sam.DynamicPredicate package is an open-source project available on GitHub. You can view the source code and contribute to its development or report issues.
GitHub Repository: Sam.DynamicPredicate on GitHub
Issues and Contributions: Feel free to explore the codebase, report any issues, or suggest improvements through GitHub Issues.
This transparency and accessibility ensure that the project is community-driven and welcomes contributions, fostering continuous improvement and reliability.
Conclusion
The Sam.DynamicPredicate package is a powerful and practical tool for dynamic filtering in LINQ. By providing capabilities to convert predicate strings into LINQ expressions, this package helps developers create queries easily and with high flexibility. Using this package, you can have cleaner, more readable, and maintainable code, improving the performance of your applications.
Using the Sam.DynamicPredicate package allows you to quickly and dynamically respond to new filter conditions without rewriting code, thereby increasing your productivity.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.1 is compatible. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.