百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
Q

QueryKit

> 后端框架
开源

️ QueryKit 是一款 .NET 库,通过提供流畅、直观的筛选和排序语法,使查询数据更加简单。

188 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

️ QueryKit 是一款 .NET 库,通过提供流畅、直观的筛选和排序语法,使查询数据更加简单。

QueryKit ️

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.

Getting Started

bash
dotnet add package QueryKit

If we wanted to apply a filter to a DbSet called People, we just have to do something like this:

csharp
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:

csharp
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:

csharp
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.

Filtering

Usage

To apply filters to your queryable, you just need to pass an input string with your filtering input to ApplyQueryKitFilter off of a queryable:

csharp
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

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.

Basic Syntax

Use parentheses with comma-separated property names followed by an operator and value:

csharp
// 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 Email

Exact match on any of several properties:

csharp
var input = """(Status, Type, Category) == "Active" """;
// Finds records where Status, Type, OR Category equals "Active"

Numeric comparison across multiple fields:

csharp
var input = """(Age, Rating, Score) > 25""";
// Finds records where Age, Rating, OR Score is greater than 25

Negative operators (NOT contains):

csharp
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:

csharp
var input = """(Status, Type) != "Inactive" """;
// Finds records where Status != "Inactive" AND Type != "Inactive"
// Both fields must not equal "Inactive"

Advanced Usage

Combined with other conditions:

csharp
var input = """(FirstName, LastName) @=* "smith" && Age > 25 && Status == "Active" """;
// Search for "smith" in name fields AND apply additional filters

Multiple property lists in one query:

csharp
var input = """(FirstName, LastName) @=* "john" && (Email, Phone) @=* "555" """;
// Search across different property groups

Complex logical expressions:

csharp
var input = """((FirstName, LastName) @=* "smith" || Age == 30) && Status == "Active" """;
// Combine property list grouping with parentheses and other operators

Nested properties:

csharp
var input = """(Author.Name, Author.Email, Title) @=* "john" """;
// Search across nested object properties

With numeric comparisons:

csharp
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).

Child Property Comparisons

You can also compare child properties to root properties or other child properties:

csharp
// 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:

  • Nested Objects: Author.Name, Email.Value
  • All Operators: ==, !=, >, =, ` 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";

Supported Features

  • All Numeric Types: int, decimal, double, float, long, short, byte and their nullable variants
  • Automatic Type Conversion: Compatible numeric types are automatically converted for calculations
  • Parentheses: Use parentheses to control calculation order and group expressions
  • Entity Framework Translation: All arithmetic expressions are translated to efficient SQL queries
  • Property-to-Property: Can mix property references with literal values in the same expression

Examples

csharp
// 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();

Filtering Projections

You can also filter on queryable projections like so:

csharp
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();

Filtering Raw SQL Projections

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:

  • Raw SQL projections work seamlessly with QueryKit's filtering and sorting
  • You can include computed fields (like StudentFullName) and nested fields from joins (like CourseStartDate)
  • Property mappings allow you to use friendly query names that differ from the DTO property names
  • The resulting queryable can be further filtered and sorted by QueryKit before materializing to a list

Filtering Collections

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:

csharp
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 %:

csharp
var input = """"Ingredients.Stock %>= 1"""";

Nested collections can also be filtered:

csharp
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 *):

csharp
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:

csharp
var input = """"Ingredients #>= 0"""";

Filtering Enums

You can filter enums with their respective integer value:

csharp
var input = "BirthMonth == 1";

public enum BirthMonthEnum
{
    January = 1,
    February = 2,
    //...
}

Settings

Property Settings

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 property
csharp
var input = $"""first == "Jane" || Age > 10""";
var config = new QueryKitConfiguration(config =>
{
    config.Property(x => x.FirstName)
            .HasQueryName("first");
    config.Property(x => x.Age)
      		.PreventFilter();
});

Derived Properties

You can also expose custom derived properties for consumption. Just be sure that Linq can handle them in a db

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#dotnetfilterfilteringgraphql-alternative

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架