MySqlApi 1.2.0

dotnet add package MySqlApi --version 1.2.0
                    
NuGet\Install-Package MySqlApi -Version 1.2.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="MySqlApi" Version="1.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MySqlApi" Version="1.2.0" />
                    
Directory.Packages.props
<PackageReference Include="MySqlApi" />
                    
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 MySqlApi --version 1.2.0
                    
#r "nuget: MySqlApi, 1.2.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 MySqlApi@1.2.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=MySqlApi&version=1.2.0
                    
Install as a Cake Addin
#tool nuget:?package=MySqlApi&version=1.2.0
                    
Install as a Cake Tool

MySqlApi

基于 Dapper + MySqlConnector 的轻量 MySQL ORM 封装类库。

  • 类库项目,可打包上传至 NuGet
  • 数据表实体模型由使用方定义,通过特性标注映射关系
  • 统一门面 MySqlClient,屏蔽底层连接、工厂与仓储实现细节
  • 提供表结构与数据表级泛型增删改查
  • 同步与异步 API 均支持

安装依赖

项目已声明以下 NuGet 依赖:

包名 说明
Dapper 微型 ORM,负责 SQL 执行与结果映射
MySqlConnector 高性能 MySQL ADO.NET 驱动

定义数据表模型

使用特性将外部实体类映射到数据表:

using MySqlApi.Attributes;
[Table("users")] public class User { [Key] [AutoIncrement] [Column("id")] public long Id { get; set; }
[Column("user_name")]
public string UserName { get; set; } = string.Empty;

[Column("age")]
public int Age { get; set; }

[Column("email")]
public string? Email { get; set; }

[Column("created_at")]
public DateTime CreatedAt { get; set; }

[NotMapped]
public string? Remark { get; set; }

说明:

  • [Table] 标注表名;省略时使用类名

  • [Column] 标注字段名;省略时使用属性名

  • [Key] 标注主键;省略时默认使用名为 Id 的属性

  • [UniqueKey] 标注唯一键,建表时生成唯一约束

  • [Index] 标注普通索引;[Index("name")] 指定索引名,同名可组合联合索引

  • [AutoIncrement] 标注自增字段(插入时忽略,由数据库生成)

  • [NotNull] 强制字段 NOT NULL(针对 string 等引用类型)

  • [MaxLength] 指定字段长度,如 [MaxLength(64)]

  • [ColumnType] 覆盖自动映射的字段类型,如 [ColumnType("TEXT")]

  • [Precision] 指定 decimal 精度,如 [Precision(18, 2)]

  • [Default] 指定字段默认值:数值/布尔/枚举按字面量输出,字符串对 string 属性自动加引号,对 decimal/日期/Guid 属性按类型解析(如 [Default("0.00")][Default("2024-01-01")])

  • [DefaultSql] 指定默认值的原始 SQL 表达式,如 [DefaultSql("CURRENT_TIMESTAMP")]

  • [NotMapped] 标注不参与映射的属性

  • [ForeignKey] 标注外键引用

快速开始

通过 MySqlClient.Connect 获取门面实例,底层按连接字符串复用连接池:

csharp using MySqlApi;
var client = MySqlClient.Connect( 
    userName: "root", password: "123456", 
    database: "test", host: "localhost"); // port 可选,默认 3306
// 判断数据表是否存在,不存在则自动创建 
if (!client.TableExists<User>()) 
    client.CreateTable<User>();

数据表增删改查(泛型 CRUD)

// 增:Insert 返回受影响行数,自增主键自动回填到实体 
var user = new User { UserName = "张三", Age = 20, Email = "zhangsan@example.com" }; 
client.Insert(user); var newId = user.Id; // 自增主键已回填
// 或直接返回自增 Id 
var newId2 = client.InsertReturnId(new User { UserName = "李四", Age = 21 });
// 批量增(多值 INSERT,自动分批) 
var affected = client.InsertBatch(new[] 
{
    new User { UserName = "王五", Age = 22 }, 
    new User { UserName = "赵六", Age = 23 },
});
// 删 
client.Delete<User>(1); // 按主键删除 
client.DeleteWhere<User>("age > @age", new { age = 30 }); // 按条件删除
// 改 
var u = client.GetById<User>(newId); 
u!.Age = 25; client.Update(u); // 按主键更新
// 条件更新(匿名对象,属性名与实体一致,自动映射列名) 
client.UpdateColumns<User>(new { Age = 30 }, "id = @id", new { id = newId });
// 条件更新(自由 SQL SET 子句) 
client.UpdateWhere<User>("age = @age", "id > @id", new { age = 30, id = 5 });
// 查 
var all = client.GetAll<User>(); 
var first = client.GetById<User>(newId); 
var list = client.Query<User>(
    "age >= @age", new { age = 18 }, orderBy: "id DESC", limit: 10
); 
var total = client.Count<User>(); 
var exists = client.Exists<User>(newId);
// 分页查询 
var page = client.QueryPaged<User>(
    "age >= @age", new { age = 18 }, orderBy: "id DESC", pageIndex: 1, pageSize: 10
); 
var pageItems = page.Items; // 当前页数据 
var pageTotal = page.Total; // 总记录数 
var pageIndex = page.PageIndex; // 当前页码 
var pageCount = page.TotalPages; // 总页数

异步 API

所有读写操作均提供对应的异步方法,返回 Task / Task<T>,可通过 CancellationToken 取消:

if (!await client.TableExistsAsync<User>()) 
    await client.CreateTableAsync<User>();
await client.InsertAsync(user); 
var newId = await client.InsertReturnIdAsync(
    new User { UserName = "李四", Age = 21 }
); 
var affected = await client.InsertBatchAsync(new[] 
{
    new User { UserName = "王五", Age = 22 }
});
var byId = await client.GetByIdAsync<User>(newId); 
var list = await client.QueryAsync<User>("age >= @age", new { age = 20 }, orderBy: "id DESC", limit: 10);
var page = await client.QueryPagedAsync<User>(pageIndex: 1, pageSize: 2); 
var total = await client.CountAsync<User>(); 
var exists = await client.ExistsAsync<User>(newId);
await client.UpdateAsync(user); 
await client.UpdateColumnsAsync<User>(new { Age = 35 }, "id = @id", new { id = newId }); 
await client.UpdateWhereAsync<User>("age = @age", "user_name = @name", new { age = 40, name = "赵六" });
await client.DeleteAsync<User>(newId); 
await client.DeleteWhereAsync<User>("age > @age", new { age = 100 });

API 概览

MySqlClient 提供(泛型参数 T 为数据表实体,where T : class):

分类 方法
连接 Connect(userName, password, database, host, port = 3306)
表结构 TableExists / TableExistsAsyncCreateTable / CreateTableAsync
Insert / InsertAsyncInsertReturnId / InsertReturnIdAsyncInsertBatch / InsertBatchAsync
Delete / DeleteAsyncDeleteWhere / DeleteWhereAsync
Update / UpdateAsyncUpdateColumns / UpdateColumnsAsyncUpdateWhere / UpdateWhereAsync
GetById / GetByIdAsyncGetAll / GetAllAsyncQuery / QueryAsyncQueryPaged / QueryPagedAsyncCount / CountAsyncExists / ExistsAsync

打包发布 NuGet

dotnet pack MySqlApi/MySqlApi.csproj -c Release -o ./nupkg

生成的 .nupkg 文件位于 ./nupkg 目录,可通过 dotnet nuget push 发布。

Product Compatible and additional computed target framework versions.
.NET 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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
1.2.0 52 9/8/2026
1.1.0 60 9/7/2026
1.0.0 65 8/29/2026