Kuery 0.2.0
dotnet add package Kuery --version 0.2.0
NuGet\Install-Package Kuery -Version 0.2.0
<PackageReference Include="Kuery" Version="0.2.0" />
<PackageVersion Include="Kuery" Version="0.2.0" />
<PackageReference Include="Kuery" />
paket add Kuery --version 0.2.0
#r "nuget: Kuery, 0.2.0"
#:package Kuery@0.2.0
#addin nuget:?package=Kuery&version=0.2.0
#tool nuget:?package=Kuery&version=0.2.0
Kuery
Simple ORM for .NET
Install
Install Kuery from NuGet.
Usage
The library contains simple attributes that you can use to control the construction of tables. In a simple todo program, you might use:
[Table("todo")]
public class Todo
{
[PrimaryKey]
[Column("id")]
[AutoIncrement]
public int Id { get; set; }
[NotNull]
[Column("name")]
public string Name { get; set; }
[Column("description")]
public string Description { get; set; }
[NotNull]
[Column("done")]
public bool IsDone { get; set; }
[NotNull]
[Column("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[NotNull]
[Column("updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
}
In addition to Kuery attributes, the mapper also supports these .NET attributes:
System.ComponentModel.DataAnnotations.Schema.TableSystem.ComponentModel.DataAnnotations.Schema.ColumnSystem.ComponentModel.DataAnnotations.RequiredSystem.ComponentModel.DataAnnotations.MaxLengthSystem.ComponentModel.DataAnnotations.StringLength
Synchronous API
You can insert rows in the database using Insert.
If the table contains an auto-incremented primary key,
then the value for that key will be available to you after the insert:
var todo = new Todo()
{
Name = "Study English",
Description = "Study English Everyday",
CreatedAt = DateTimeOffset.Now,
UpdatedAt = DateTimeOffset.Now,
});
using var connection = new Microsoft.Data.Sqlite.SqliteConnection("Your connection string");
connection.Open();
connection.Insert(todo);
Similar methods exist for Update and Delete.
All write methods accept an optional IDbTransaction.
The most straightforward way to query for data is using the Table method.
This can take predicates for constraining via WHERE clauses and/or adding ORDER BY clauses:
List<Todo> todos = connection.Table<Todo>()
.Where(x => x.Name == "Study English")
.ToList();
Table<T>() also supports:
OrderBy/OrderByDescending/ThenBy/ThenByDescendingSkip/Take/ElementAtCount/First/FirstOrDefaultDelete()andDelete(predicate)
Other synchronous APIs:
- Batch writes:
InsertAll,UpdateAll,InsertOrReplace - Single row retrieval:
Find(pk),Find(predicate),Get(pk),Get(predicate) - Manual SQL:
Query<T>(sql, param),Query(type, sql, param),FindWithQuery<T>,Execute,ExecuteScalar<T>
Asynchronous API
You can insert rows in the database using InsertAsync.
If the table contains an auto-incremented primary key,
then the value for that key will be available to after the insert:
var todo = new Todo()
{
Name = "Study English",
Description = "Study English Everyday",
CreatedAt = DateTimeOffset.Now,
UpdatedAt = DateTimeOffset.Now,
});
using var connection = new Microsoft.Data.Sqlite.SqliteConnection("Your connection string");
await connection.OpenAsync();
await connection.InsertAsync(todo);
Similar methods exist for UpdateAsync and DeleteAsync.
Querying for data is most straightforwardly done using the Table method.
This will return a TableQuery instance back,
whereupon you can add predicates for constraining via WHERE clauses and/or adding ORDER BY.
The database is not physically touched until one of the special retrieval
methods - ToListAsync, FirstAsync, or FirstOrDefaultAsync - is called.
List<Todo> todos = await connection.Table<Todo>()
.Where(x => x.Name == "Study English")
.ToListAsync();
Async API also provides:
- Batch writes:
InsertAllAsync,UpdateAllAsync,InsertOrReplaceAsync - Single row retrieval:
FindAsync(pk),FindAsync(predicate),GetAsync(pk),GetAsync(predicate) - LINQ execution helpers:
ToListAsync,CountAsync,FirstAsync,FirstOrDefaultAsync - Manual SQL:
QueryAsync<T>(sql, param),FindWithQueryAsync<T>,ExecuteAsync,ExecuteScalarAsync<T>
Most async methods accept CancellationToken.
IQueryable API (Query<T>())
You can also compose SQL SELECT queries through LINQ by using Query<T>().
The query pipeline translates LINQ to typed SQL expressions and constructs results directly from the selected columns. It supports SQLite, PostgreSQL, SQL Server, and MySQL without an EF Core dependency, change tracking, or migrations.
var products = await connection.Query<Product>()
.Where(p => p.Code == "0001")
.OrderBy(p => p.Code)
.ToListAsync();
var deleted = await connection.Query<Product>()
.Where(p => p.Id == id)
.ExecuteDeleteAsync();
var updated = await connection.Query<Product>()
.Where(p => p.Code == "0001")
.ExecuteUpdateAsync(setters => setters
.SetProperty(p => p.Name, p => p.Name + " (updated)"));
SQL translation currently supports (including async equivalents where applicable):
- Query shape:
Where,Select,OrderBy/ThenBy,Order/OrderDescending,Reverse,Skip,Take, parameterlessDefaultIfEmpty - Retrieval/aggregation:
Count,LongCount,Any,All,First,FirstOrDefault,Single,SingleOrDefault,Last,LastOrDefault,Sum,Min,Max,Average,MinBy,MaxBy - Grouping:
GroupBy(single key and composite key),HAVING, final groups, and ordered top elements - Joins:
Join, composite-key join, chained joins,LeftJoin/RightJoin(.NET 10), KueryFullJoin, the existing left join pattern, and finalGroupJoin - Set operations:
Distinct,Concat,Union,Intersect,Except - Membership: terminal and subquery
Contains(null-awareEXISTS; entity primary-key comparison) - Types:
Cast,OfType, and query-only TPH discriminator attributes - Subqueries:
Any(EXISTS),SelectMany(cross joins, predicate joins, and provider-specific lateral joins) - Data modification:
ExecuteDelete/ExecuteDeleteAsync(requiresWhere),ExecuteUpdate/ExecuteUpdateAsync - Built-in expression translation:
- String:
Contains,StartsWith,EndsWith,Replace,Substring,Trim,TrimStart,TrimEnd,Length,IndexOf,string.IsNullOrEmpty,string.IsNullOrWhiteSpace - Math:
Math.Abs,Math.Round,Math.Floor,Math.Ceiling,Math.Max,Math.Min,Math.Pow,Math.Sqrt,Math.Log,Math.Log10 - Date/Time:
DateTime.Now,DateTime.UtcNow,DateTime.Date,DateTime.DayOfWeek,AddDays,AddMonths,AddYears,AddHours,AddMinutes,AddSeconds, and members such asYear,Month,Day,Hour,Minute,Second - Type conversion:
Convert.ToInt16,Convert.ToInt32,Convert.ToInt64,Convert.ToDouble,Convert.ToSingle,Convert.ToBoolean,Convert.ToString,.ToString() - Other: null coalescing (
??), ternary conditional (?:), bitwise operators (&,|,^,~), andKueryFunctions.Like(...)
- String:
Unsupported LINQ operators throw NotSupportedException.
Computed projections can be filtered, sorted, and aggregated on the server:
var summaries = await connection.Query<Product>()
.Select(p => new { p.Name, Score = p.Price * p.TotalSales })
.Where(p => p.Score > 100)
.OrderByDescending(p => p.Score)
.Take(10)
.ToListAsync();
Operator order is preserved: Take(10).Where(predicate) filters the first ten rows,
and Select(p => p.Name).Distinct().Count() counts distinct names, including null.
Nullable equality/inequality and collection Contains use C# null semantics.
Reverse/Last/LastOrDefault require an explicit OrderBy; out-of-range ElementAt throws
ArgumentOutOfRangeException. Queries combined in joins, set operations, or subqueries
must use the same connection. Use AsEnumerable() to switch explicitly to client processing.
See SQL support and query pipeline design for capabilities and limitations. The internal class names and compilation stages follow EF Core where practical. The 44-operator coverage matrix defines the comparison scope and verification status. See the EF Core alignment guide for corresponding source locations and intentional differences.
Use FromSql<T>() to compose LINQ over a parameterized SELECT. ToQueryString()
returns generated SQL for inspection, and TagWith() adds a comment. The async query
extensions offer terminal operators, collection helpers, and row streaming through
AsAsyncEnumerable().
Manual SQL
using var connection = new Microsoft.Data.Sqlite.SqliteConnection("Your connection string");
connection.Open();
IEnumerable<Todo> todos = connection.Query<Todo>(
"SELECT * FROM todo WHERE name = $name",
new { name = "Study English" });
You can also use async manual SQL APIs:
IEnumerable<Todo> todos = await connection.QueryAsync<Todo>(
"SELECT * FROM todo WHERE name = $name",
new { name = "Study English" });
Running Tests
The test project has three execution modes:
fast(default local workflow): SQLite tests onlyintegration: SQL Server + PostgreSQL + MySQL testsall: fast + integration
Fast (SQLite only)
./test/run-fast-tests.sh
Integration (SQL Server + PostgreSQL + MySQL)
Requires Docker.
./test/run-integration-tests.sh
This script starts test databases via test/docker-compose.test.yml, runs SQL Server/PostgreSQL/MySQL tests, then cleans up containers.
CI
GitHub Actions runs:
fastjob: SQLite-only testsintegrationjob: SQL Server + PostgreSQL + MySQL tests via DockerRelease NuGet Packageworkflow: validates the release tag, runs both test suites, and publishes to NuGet.org using Trusted Publishing when a GitHub Release is published. See publishing packages for initial setup and release steps.
All tests
./test/run-all-tests.sh
Environment variables (optional)
Fixtures now support environment variable overrides.
- PostgreSQL:
KUERY_TEST_PG_HOST,KUERY_TEST_PG_PORT,KUERY_TEST_PG_USERNAME,KUERY_TEST_PG_PASSWORD,KUERY_TEST_PG_MASTER_DB - SQL Server:
KUERY_TEST_SQLSERVER_HOST,KUERY_TEST_SQLSERVER_INTEGRATED_SECURITY,KUERY_TEST_SQLSERVER_USERNAME,KUERY_TEST_SQLSERVER_PASSWORD,KUERY_TEST_SQLSERVER_MASTER_DB - MySQL:
KUERY_TEST_MYSQL_HOST,KUERY_TEST_MYSQL_PORT,KUERY_TEST_MYSQL_USERNAME,KUERY_TEST_MYSQL_PASSWORD,KUERY_TEST_MYSQL_MASTER_DB
Contribution
- Fork it ( http://github.com/tnakamura/Kuery )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create new Pull Request
License
Author
| 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. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. 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.0
- Microsoft.Bcl.AsyncInterfaces (>= 10.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
## v0.2.0
- Rebuilt the LINQ-to-SQL pipeline with typed SQL translation, direct result materialization, and compiled query caching.
- Added MySQL support alongside SQLite, PostgreSQL, and SQL Server.
- Expanded LINQ support for outer joins, set operations, grouping, subqueries, and query-only table-per-hierarchy inheritance.
- Added `FromSql<T>()` for composing LINQ over parameterized SQL, `ToQueryString()` and `TagWith()` for inspecting and annotating queries, and `AsAsyncEnumerable()` for async streaming.
- Added `ExecuteUpdate` and `ExecuteDelete`, along with async equivalents, for set-based changes. Added support for DataAnnotations mapping attributes.
- **Breaking changes.** `KueryQueryProvider` and `KueryQueryable<T>` are now internal. Use `IQueryProvider` and `IQueryable<T>` in consuming code. `BaseTableQuery` was removed. Use `TableQuery<T>` or `IEnumerable<T>` as appropriate.