Syntax inspired from KQL (specification)
var collection = new List<Person>();
var queryBuilder = new QueryBuilder<Person>();
queryBuilder.AddHandler<string>("name", (obj, value) => obj.FullName.Contains(value, StringComparison.OrdinalIgnoreCase));
queryBuilder.AddRangeHandler<int>("age", (obj, value) => value.IsInRange((int)(DateTime.UtcNow - obj.DateOfBirth).TotalDays / 365));
var query = queryBuilder.Build("name:sample query");
query.Evaluate(new Person("John Doe", new DateTime(2000, 1, 1)));
record Person(string FullName, DateTime DateOfBirth);- Logical operators
NOT,AND,OR - Priority using
(,) AddHandler: supported operators::AddRangeHandler: supported operators::,<,<=,>,>=,..(range)SetTextFilterHandlermatches all non-bound filters- Special values:
today,yesterday,this week,this month,last month,this year,last year
Examples:
name:johnorname=johnname:"john doe"name<>johnor-name:johnorNOT name:john(name:"john doe" OR name:jane) AND age>21created:"this week"age:13..19(lower and upper bound are included)age>=21is_open:true free form textis_open:true AND NOT "free form text"
The ExpressionQueryBuilder<T> class creates Expression<Func<T, bool>> objects that can be translated to SQL by Entity Framework Core, allowing you to apply query language filters directly to database queries.
// Define a query builder for your entity
var queryBuilder = new ExpressionQueryBuilder<Person>();
// Add handlers for string properties (uses Contains for partial matching).
// Case sensitivity follows the provider: the database collation for EF Core, ordinal for LINQ to Objects.
// Pass a StringComparison to force one, but note that EF Core cannot translate it.
queryBuilder.AddHandler("name", person => person.FullName);
// Add handlers for comparable types (supports range and comparison operators)
queryBuilder.AddHandler<int>("age", person => person.Age);
queryBuilder.AddHandler<DateTime>("created", person => person.CreatedAt);
// Optional: handle free-text search across multiple fields
queryBuilder.SetFreeTextHandler(text =>
person => person.FullName.Contains(text) || person.Email.Contains(text));
// Build the query
var query = queryBuilder.Build("name:john AND age>=21");
// Apply to an IQueryable (e.g., EF Core DbSet)
var results = await dbContext.People
.Apply(query)
.ToListAsync();The ExpressionQueryBuilder<T> supports the same query syntax as QueryBuilder<T>, including:
- String matching with
:operator - Comparison operators:
<,<=,>,>= - Range syntax:
age:18..25 - Logical operators:
AND,OR,NOT - Parentheses for grouping