Sqlx 0.6.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Sqlx --version 0.6.0
                    
NuGet\Install-Package Sqlx -Version 0.6.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sqlx" Version="0.6.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sqlx" Version="0.6.0" />
                    
Directory.Packages.props
<PackageReference Include="Sqlx" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Sqlx --version 0.6.0
                    
#r "nuget: Sqlx, 0.6.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Sqlx@0.6.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Sqlx&version=0.6.0
                    
Install as a Cake Addin
#tool nuget:?package=Sqlx&version=0.6.0
                    
Install as a Cake Tool

Sqlx

NuGet License .NET LTS

编译时源生成器,构建类型安全、高性能的 .NET 数据库访问层。零运行时反射,完全 AOT 兼容。

核心特性

  • 编译时生成 - 零反射,接近原生 ADO.NET 性能
  • 类型安全 - 编译时捕获 SQL 错误
  • 多数据库 - SQLite、PostgreSQL、MySQL、SQL Server、Oracle、DB2
  • 智能模板 - 占位符自动适配不同数据库方言
  • AOT 兼容 - 完全支持 Native AOT

快速开始

dotnet add package Sqlx
// 1. 定义实体
[SqlxEntity, SqlxParameter, TableName("users")]
public class User
{
    [Key] public long Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

// 2. 定义仓储接口
public interface IUserRepository : ICrudRepository<User, long>
{
    [SqlTemplate("SELECT {{columns}} FROM {{table}} WHERE age >= @minAge")]
    Task<List<User>> GetAdultsAsync(int minAge);
}

// 3. 实现仓储(代码自动生成)
[SqlDefine(SqlDefineTypes.SQLite)]
[RepositoryFor(typeof(IUserRepository))]
public partial class UserRepository(DbConnection connection) : IUserRepository { }

// 4. 使用
await using var conn = new SqliteConnection("Data Source=app.db");
var repo = new UserRepository(conn);
var adults = await repo.GetAdultsAsync(18);

SQL 模板占位符

占位符自动适配不同数据库方言:

占位符 说明 示例输出
{{table}} 表名(带方言引号) "users" (PostgreSQL)
{{columns}} 所有列名 id, name, age
{{columns --exclude Id}} 排除指定列 name, age
{{values --exclude Id}} 参数占位符 @name, @age
{{set --exclude Id}} UPDATE SET 子句 name = @name
{{if notnull=param}}...{{/if}} 条件包含 动态 SQL

各数据库生成的 SQL:

数据库 生成的 SQL
SQLite SELECT [id], [name] FROM [users] WHERE is_active = 1
PostgreSQL SELECT "id", "name" FROM "users" WHERE is_active = true
MySQL SELECT `id`, `name` FROM `users` WHERE is_active = 1

内置仓储接口

继承 ICrudRepository<TEntity, TKey> 获得标准 CRUD 方法:

public interface IUserRepository : ICrudRepository<User, long>
{
    // 继承方法: GetByIdAsync, GetAllAsync, InsertAndGetIdAsync, 
    // UpdateAsync, DeleteAsync, CountAsync, ExistsAsync...
    
    // 自定义方法
    [SqlTemplate("SELECT {{columns}} FROM {{table}} WHERE name LIKE @pattern")]
    Task<List<User>> SearchByNameAsync(string pattern);
}

条件占位符

// 动态搜索:只在参数有值时添加条件
[SqlTemplate(@"
    SELECT {{columns}} FROM {{table}} WHERE 1=1 
    {{if notnull=name}}AND name LIKE @name{{/if}}
    {{if notnull=minAge}}AND age >= @minAge{{/if}}
")]
Task<List<User>> SearchAsync(string? name, int? minAge);

IQueryable 查询构建器

使用标准 LINQ 语法构建类型安全的 SQL 查询:

using Sqlx;

// 基本查询
var sql = SqlQuery.ForSqlite<User>()
    .Where(u => u.Age >= 18 && u.IsActive)
    .OrderBy(u => u.Name)
    .Take(10)
    .ToSql();
// SELECT * FROM [User] WHERE ([age] >= 18 AND [is_active] = 1) ORDER BY [name] ASC LIMIT 10

// 投影查询
var sql = SqlQuery.ForPostgreSQL<User>()
    .Where(u => u.Name.Contains("test"))
    .Select(u => new { u.Id, u.Name })
    .ToSql();
// SELECT "id", "name" FROM "User" WHERE "name" LIKE '%' || 'test' || '%'

// 参数化查询
var (sql, parameters) = SqlQuery.ForSqlServer<User>()
    .Where(u => u.Age > 18)
    .ToSqlWithParameters();
// SQL: SELECT * FROM [User] WHERE [age] > @p0
// Parameters: { "@p0": 18 }

支持的 LINQ 方法:

  • Where - 条件过滤(支持 String/Math 方法、null 合并、条件表达式)
  • Select - 投影(支持匿名类型、函数调用)
  • OrderBy / OrderByDescending / ThenBy / ThenByDescending - 排序
  • Take / Skip - 分页
  • GroupBy - 分组
  • Distinct - 去重

支持的函数:

  • String: Contains, StartsWith, EndsWith, ToUpper, ToLower, Trim, Substring, Replace, Length
  • Math: Abs, Round, Floor, Ceiling, Sqrt, Pow, Min, Max

表达式查询(仓储模式)

// 在仓储中使用 LINQ 表达式
[SqlTemplate("SELECT {{columns}} FROM {{table}} WHERE {{where --param predicate}}")]
Task<List<User>> GetWhereAsync(Expression<Func<User, bool>> predicate);

// 使用
var adults = await repo.GetWhereAsync(u => u.Age >= 18 && u.IsActive);

批量执行

var users = new List<User> { new() { Name = "Alice" }, new() { Name = "Bob" } };
var sql = "INSERT INTO users (name) VALUES (@name)";
await connection.ExecuteBatchAsync(sql, users, UserParameterBinder.Default);

性能对比

基于 BenchmarkDotNet 测试(SQLite 内存数据库,10000 条记录):

.NET 10 性能(最新 LTS)

场景 Sqlx vs Dapper.AOT Sqlx vs FreeSql
单条查询 快 16% 快 7.0x
插入操作 持平 快 2.0x
更新操作 快 9% 快 4.2x
删除操作 持平 快 5.4x
计数操作 持平 快 50x

测试环境: .NET 10.0.2 (LTS), BenchmarkDotNet 0.15.7, AMD Ryzen 7 5800H

详细数据见 性能基准测试

支持的数据库

数据库 方言枚举 .NET 版本
SQLite SqlDefineTypes.SQLite .NET 8.0+
PostgreSQL SqlDefineTypes.PostgreSql .NET 8.0+
MySQL SqlDefineTypes.MySql .NET 8.0+
SQL Server SqlDefineTypes.SqlServer .NET 8.0+
Oracle SqlDefineTypes.Oracle .NET 8.0+
IBM DB2 SqlDefineTypes.DB2 .NET 8.0+

推荐: .NET 10 (LTS) - 支持到 2028 年 11 月

更多文档

许可证

MIT License - 详见 LICENSE.txt

Product 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 is compatible.  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 is compatible.  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 is compatible.  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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.1

    • No dependencies.
  • net10.0

    • No dependencies.
  • net8.0

    • No dependencies.
  • net9.0

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

Version Downloads Last Updated
0.6.8 96 2/7/2026
0.6.7 81 2/5/2026
0.6.6 80 2/3/2026
0.6.5 97 1/23/2026
0.6.4 87 1/22/2026
0.6.3 86 1/22/2026
0.6.2 99 1/16/2026
0.6.1 84 1/15/2026
0.6.0 83 1/15/2026
0.5.0 107 1/11/2026
0.4.0 213 10/27/2025
0.3.0 284 10/2/2025
0.2.0 227 9/21/2025
0.1.4-dev 210 8/31/2025
0.1.3-dev 118 8/23/2025
0.1.2-dev 177 8/20/2025
0.1.1-dev 149 8/17/2025
0.1.0-dev 164 7/27/2025