️ QueryKit 是一款 .NET 库,通过提供流畅、直观的筛选和排序语法,使查询数据更加简单。
QueryKit is a .NET library that makes it easier to query your data by providing a fluent and intuitive syntax for filtering and sorting. The main use case is a lighter weight subset of OData or GraphQL for parsing external filtering and sorting inputs to provide more granular consumption (e.g. a React UI provides filtering controls to filter a worklist). It's inspired by Sieve, but with some differences.
dotnet add package QueryKitIf we wanted to apply a filter to a DbSet called People, we just have to do something like this:
var filterInput = """FirstName == "Jane" && Age > 10""";
var people = _dbContext.People
.ApplyQueryKitFilter(filterInput)
.ToList();QueryKit will automatically translate this into an expression for you. You can even customize your property names:
var filterInput = """first == "Jane" && Age > 10""";
var config = new QueryKitConfiguration(config =>
{
config.Property(x => x.FirstName).HasQueryName("first");
});
var people = _dbContext.People
.ApplyQueryKitFilter(filterInput, config)
.ToList();Sorting works too:
var filterInput = """first == "Jane" && Age > 10""";
var config = new QueryKitConfiguration(config =>
{
config.Property(x => x.FirstName).HasQueryName("first");
});
var people = _dbContext.People
.ApplyQueryKitFilter(filterInput, config)
.ApplyQueryKitSort("first, Age desc", config)
.ToList();And that's the basics! There's no services to inject or global set up to worry about, just apply what you want and call it a day. For a full list of capables, see below.
To apply filters to your queryable, you just need to pass an input string with your filtering input to ApplyQueryKitFilter off of a queryable:
var people = _dbContext.People.ApplyQueryKitFilter("Age
{
config.Property(x => x.FirstName)
.HasQueryName("first")
.PreventSort();
});
var people = _dbContext.People
.ApplyQueryKitFilter(@$"first == "Jane" && Age | N/A | #> |
| Less Than | = | N/A | #>= |
| Less Than Or Equal | `Sounds Like` and `Does Not Sound Like` requires a soundex configuration on your DbContext. For more info see [the docs below](#soundex)
Here's an example for the `in` operator:
```c#
var input = """(Age ^^ [20, 30, 40]) && (BirthMonth ^^* ["January", "February", "March"]) || (Id ^^ ["6d623e92-d2cf-4496-a2df-f49fa77328ee"])""";Property list grouping allows you to apply a single comparison operation across multiple properties, making it easy to search for a value in any of several fields without writing repetitive conditions.
Use parentheses with comma-separated property names followed by an operator and value:
// Search for "paul" in either FirstName OR LastName
var input = """(FirstName, LastName) @=* "paul" """;
// Equivalent to:
// FirstName @=* "paul" || LastName @=* "paul"
…
c#
var input = """(FirstName, LastName, Email) @=* "john" """;
// Finds records where "john" appears in FirstName OR LastName OR EmailExact match on any of several properties:
var input = """(Status, Type, Category) == "Active" """;
// Finds records where Status, Type, OR Category equals "Active"Numeric comparison across multiple fields:
var input = """(Age, Rating, Score) > 25""";
// Finds records where Age, Rating, OR Score is greater than 25Negative operators (NOT contains):
var input = """(FirstName, LastName) !@=* "test" """;
// Finds records where "test" is NOT in FirstName AND NOT in LastName
// Both fields must not contain "test"Not equals:
var input = """(Status, Type) != "Inactive" """;
// Finds records where Status != "Inactive" AND Type != "Inactive"
// Both fields must not equal "Inactive"Combined with other conditions:
var input = """(FirstName, LastName) @=* "smith" && Age > 25 && Status == "Active" """;
// Search for "smith" in name fields AND apply additional filtersMultiple property lists in one query:
var input = """(FirstName, LastName) @=* "john" && (Email, Phone) @=* "555" """;
// Search across different property groupsComplex logical expressions:
var input = """((FirstName, LastName) @=* "smith" || Age == 30) && Status == "Active" """;
// Combine property list grouping with parentheses and other operatorsNested properties:
var input = """(Author.Name, Author.Email, Title) @=* "john" """;
// Search across nested object propertiesWith numeric comparisons:
var input = """(Age, YearsOfExperience, Rating) >= 5""";
// Find records where any numeric field meets the criteria
…
c#
var input = """""Title == """lamb is great on a "gee-ro" not a "gy-ro" sandwich""" """"";
// OR
var input = """""""""Title == """"lamb is great on a "gee-ro" not a "gy-ro" sandwich"""" """"""""";
…
c#
var input = """(Title == "lamb" && ((Age >= 25 && Rating Rating""";
// Use in complex expressions
var input = """(FirstName != LastName && Age > Rating) || (Score1 21""";Property-to-property comparisons work with all comparison operators and automatically handle type conversions between compatible numeric types (e.g., comparing int with decimal).
You can also compare child properties to root properties or other child properties:
// Compare child property to root property
var input = """Author.Name == Title""";
// Compare nested child properties
var input = """Email.Value == CollectionEmail.Value""";
// Mix child and root properties in complex expressions
var input = """Author.Name != Title && Rating > Author.Score""";Child property comparisons work with:
Author.Name, Email.Value==, !=, >, =, ` 50";// Subtraction: Find records where Age - Rating is positive var input = "(Age - Rating) > 0";
// Multiplication: Find records where Price * Quantity exceeds 1000 var input = "(Price * Quantity) > 1000";
// Division: Find records where Total / Count is less than 100 var input = "(Total / Count) 100"; // Tax * Rate is calculated first
// Use parentheses to override precedence var input = "((Price + Tax) * Rate) > 100"; // Addition happens first
#### Mixing Properties and Literals
You can combine entity properties with literal numeric values:
```c#
// Property with literal
var input = "(Age - 18) >= 0"; // Age minus 18
// Multiple properties with literals
var input = "(Price * 1.1 + ShippingCost) 300 && Category == "Electronics" """;
// Multiple arithmetic comparisons
var input = "(Score1 + Score2) > 150 && (Score1 - Score2) 0.1";int, decimal, double, float, long, short, byte and their nullable variants// Calculate profit margin and filter
var profitableItems = _dbContext.Products
.ApplyQueryKitFilter("((Price - Cost) / Price) > 0.2")
.ToList();
// Find orders with high shipping ratio
var expensiveShipping = _dbContext.Orders
.ApplyQueryKitFilter("(ShippingCost / TotalAmount) > 0.15")
.ToList();
// Complex business logic in one filter
var qualifiedCustomers = _dbContext.Customers
.ApplyQueryKitFilter("""
(TotalPurchases / NumberOfOrders) > 500 &&
((LastOrderDate - FirstOrderDate) / 365) >= 2
""")
.ToList();You can also filter on queryable projections like so:
var input = $"""info @=* "{fakeAuthorOne.Name}" """;
var config = new QueryKitConfiguration(config =>
{
config.Property(x => x.AuthorInfo).HasQueryName("info");
});
var queryableRecipe = testingServiceScope.DbContext().Recipes
.Include(x => x.Author)
.Select(x => new RecipeDto
{
Id = x.Id,
Title = x.Title,
AuthorName = x.Author.Name,
AuthorInfo = x.Author.Name + " - " + x.Author.InternalIdentifier
});
var appliedQueryable = queryableRecipe.ApplyQueryKitFilter(input, config);
var recipes = await appliedQueryable.ToListAsync();QueryKit can also be used with raw SQL queries via EF Core's SqlQueryRaw. This is particularly useful when you need to work with complex SQL queries that include joins, aggregations, or database-specific functions.
You can use projections without using raw sql
Here's an example using a school domain:
…Key Points:
StudentFullName) and nested fields from joins (like CourseStartDate)You can also filter into collections with QueryKit by using most of the normal operators. For example, if I wanted to filter for recipes that only have an ingredient named salt, I could do something like this:
var input = """"Ingredients.Name == "salt" """";By default, QueryKit will use Any under the hood when building this filter, but if you want to use All, you just need to prefix the operator with a %:
var input = """"Ingredients.Stock %>= 1"""";Nested collections can also be filtered:
var input = $"""preparations == "{preparationOne.Text}" """;
var config = new QueryKitConfiguration(settings =>
{
settings.Property(x => x.Ingredients
.SelectMany(y => y.Preparations)
.Select(y => y.Text))
.HasQueryName("preparations");
});
// Act
var queryableRecipes = testingServiceScope.DbContext().Recipes;
var appliedQueryable = queryableRecipes.ApplyQueryKitFilter(input, config);
var recipes = await appliedQueryable.ToListAsync();If you want to filter a primitve collection like List you can use the Has or DoesNotHave operator (can be case insensitive with the appended *):
var input = """Tags ^$ "winner" """;
// or
var input = """Tags !^$ "winner" """;If you want to filter on the count of a collection, you can prefix some of the operators with a #. For example, if i wanted to get all recipes that have more than 0 ingredients:
var input = """"Ingredients #>= 0"""";You can filter enums with their respective integer value:
var input = "BirthMonth == 1";
public enum BirthMonthEnum
{
January = 1,
February = 2,
//...
}Filtering is set up to create an expression using the property names you have on your entity, but you can pass in a config to customize things a bit when needed.
HasQueryName() to create a custom alias for a property. For exmaple, we can make FirstName aliased to first.PreventFilter() to prevent filtering on a given propertyvar input = $"""first == "Jane" || Age > 10""";
var config = new QueryKitConfiguration(config =>
{
config.Property(x => x.FirstName)
.HasQueryName("first");
config.Property(x => x.Age)
.PreventFilter();
});You can also expose custom derived properties for consumption. Just be sure that Linq can handle them in a db
暂无开放 Issues,或尚未同步最近议题。