Sqlsugar logo

Sqlsugar

Community
znlgis
sqlsugar

Use when doing multi-database ORM operations in .NET — SqlSugarClient/SqlSugarScope, Queryable<T> chain queries, ToPageList paging, Insertable/Updateable bulk, CodeFirst.InitTables, [SplitTable] sharding, slave connection config. Also for table-name mapping mismatches, unsafe shared SqlSugarClient across threads, and MySQL utf8mb4 mojibake. SqlSugar: .NET ORM for 10+ databases.

Overview

Publisherznlgis
Repositoryopengis-skills
Skill namesqlsugar
Stars
76
Forks
12
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by znlgis on GitHub. Read the source before you install it.

Installation

Install the Sqlsugar AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/znlgis/opengis-skills/tree/main/csharp/sqlsugar
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/znlgis/opengis-skills.git /tmp/opengis-skills
mkdir -p .claude/skills
cp -r /tmp/opengis-skills/csharp/sqlsugar .claude/skills/sqlsugar
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Sqlsugar in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Sqlsugar on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Sqlsugar is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

项目地址: https://github.com/DotNetNext/SqlSugar

官方文档: https://www.donet5.com/Home/Doc

NuGet: SqlSugar / SqlSugarCore

最新版本: SqlSugarCore 5.1.4.221(.NET)/ SqlSugar 5.1.4.207(.NET Framework)(截至 2026-10,NuGet 实测)

许可证: MIT

概述

SqlSugar 主要特性:

  • 多数据库:SQL Server / MySQL / Oracle / PostgreSQL / SQLite / 达梦 / 人大金仓 / 神舟通用 / GBase / Highgo / Oscar / Tdengine / ClickHouse / OceanBase / MariaDB / Access / 行云数据库
  • Code First / DB First 双模式
  • 链式查询:Queryable<T>().Where(...).Select(...).ToList()
  • Lambda 表达式 → SQL
  • 批量操作:Insertable / Updateable / Deleteable.ExecuteCommand()
  • 多种主键策略:自增、Guid、雪花 ID
  • 读写分离 / 分库分表
  • AOT 友好(高级版)
  • 事务:UseTran 自动管理

安装

方式一:dotnet CLI

bash
dotnet add package SqlSugarCore     # .NET 6+
# 或
dotnet add package SqlSugar         # .NET Framework

方式二:PackageReference

xml
<ItemGroup>
  <PackageReference Include="SqlSugarCore" Version="5.1.4.221" />
</ItemGroup>

方式三:包管理器控制台

powershell
Install-Package SqlSugarCore -Version 5.1.4.221

验证安装

bash
dotnet list package | grep -i sqlsugar

创建客户端

csharp
using SqlSugar;

var db = new SqlSugarClient(new ConnectionConfig {
    DbType = DbType.MySql,
    ConnectionString = "server=127.0.0.1;uid=root;pwd=...;database=demo",
    IsAutoCloseConnection = true,
    InitKeyType = InitKeyType.Attribute   // 通过特性识别主键
});

db.Aop.OnLogExecuting = (sql, p) => Console.WriteLine(sql);

多数据库:使用 SqlSugarClient(List<ConnectionConfig>) 或 SqlSugarScope(推荐 DI 注入)。

在 ASP.NET Core 中注册

csharp
builder.Services.AddSingleton<ISqlSugarClient>(sp =>
    new SqlSugarScope(new ConnectionConfig {
        DbType = DbType.SqlServer,
        ConnectionString = builder.Configuration.GetConnectionString("Default"),
        IsAutoCloseConnection = true
    }));

实体定义

csharp
[SugarTable("users")]
public class User
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public int Id { get; set; }

    [SugarColumn(Length = 50, IsNullable = false)]
    public string Name { get; set; } = "";

    public int Age { get; set; }

    [SugarColumn(IsNullable = true, ColumnDataType = "datetime")]
    public DateTime? CreateTime { get; set; }

    [SugarColumn(IsIgnore = true)]
    public string Computed { get; set; } = "";
}

CRUD

csharp
// 插入(自增主键回填)
int id = db.Insertable(new User { Name = "Tom", Age = 18 })
           .ExecuteReturnIdentity();

// 批量
db.Insertable(list).ExecuteCommand();

// 更新
db.Updateable(new User { Id = 1, Name = "Tom2" }).ExecuteCommand();
db.Updateable<User>().SetColumns(u => new User { Age = u.Age + 1 })
                     .Where(u => u.Id == 1).ExecuteCommand();

// 删除
db.Deleteable<User>().Where(u => u.Id == 1).ExecuteCommand();
db.Deleteable<User>(new[] { 1, 2, 3 }).ExecuteCommand();

查询

csharp
var u  = db.Queryable<User>().First(u => u.Id == 1);

var ls = db.Queryable<User>()
           .Where(u => u.Age > 18 && u.Name.Contains("T"))
           .OrderBy(u => u.Id, OrderByType.Desc)
           .Select(u => new { u.Id, u.Name })
           .ToList();

// 分页(签名:ToPageList(pageIndex, pageSize, ref totalNumber))
int total = 0;
var page = db.Queryable<User>()
             .Where(u => u.Age > 18)
             .ToPageList(1, 20, ref total);

// JOIN
var join = db.Queryable<User, Order>((u, o) => new JoinQueryInfos(
                JoinType.Left, u.Id == o.UserId))
             .Where((u, o) => u.Age > 18)
             .Select((u, o) => new { u.Name, o.Amount })
             .ToList();

异步 API

csharp
var ls = await db.Queryable<User>().ToListAsync();
await db.Insertable(u).ExecuteCommandAsync();

事务

csharp
var result = await db.Ado.UseTranAsync(async () => {
    await db.Insertable(a).ExecuteCommandAsync();
    await db.Updateable(b).ExecuteCommandAsync();
});
if (!result.IsSuccess) Console.WriteLine(result.ErrorMessage);

Code First(自动建库/建表)

csharp
db.DbMaintenance.CreateDatabase();              // 创建库
db.CodeFirst.InitTables(typeof(User), typeof(Order));   // 创建/更新表
db.CodeFirst.InitTables<User>();

雪花 ID

csharp
public class Order {
    [SugarColumn(IsPrimaryKey = true)]
    public long Id { get; set; }      // 不要 IsIdentity
}

SnowFlakeSingle.WorkId = 1;           // 设置工作机器号

var o = new Order { Id = SnowFlakeSingle.Instance.NextId() };

读写分离

csharp
new ConnectionConfig {
    ConnectionString = "主库",
    SlaveConnectionConfigs = new() {
        new SlaveConnectionConfig { HitRate = 10, ConnectionString = "从库1" },
        new SlaveConnectionConfig { HitRate = 10, ConnectionString = "从库2" }
    }
};

写走主库,读自动负载到从库。


分表(按时间)

csharp
[SplitTable(SplitType.Month)]   // 月分表
[SugarTable("Logs_{year}{month}")]
public class Log { ... }

db.Insertable(log).SplitTable().ExecuteCommand();
db.Queryable<Log>().SplitTable(new DateTime(2024, 1, 1), new DateTime(2024, 12, 31)).ToList();

AOP(日志 / 拦截)

csharp
db.Aop.OnLogExecuting    = (sql, p) => log.Info(sql);
db.Aop.OnError           = ex      => log.Error(ex);
db.Aop.OnLogExecuted     = (sql,p) => /* 监控 */;
db.Aop.DataExecuting     = (val, e) => /* 自动填充 CreateTime */;

性能与最佳实践

  1. 批量 Insert 用 Insertable(list).UseSqlBulkCopy() 或 PageSize
  2. 大查询用 ToPageList,不要 ToList 全量
  3. 复杂表达式 抽成方法,避免反射开销
  4. Aop 异步日志,避免影响主流程
  5. 使用 SqlSugarScope 在 DI 中替代直接 SqlSugarClient

典型工作流

工作流一:新项目从建库到查询

  1. 建客户端:Web/DI 场景注入 SqlSugarScope,脚本类单次使用可用 SqlSugarClient(配 IsAutoCloseConnection = true)
  2. 定义实体:[SugarTable("表名")] + [SugarColumn(IsPrimaryKey = true)](自增加 IsIdentity = true,雪花 ID 则不要设)
  3. db.CodeFirst.InitTables<T>() 建表/更新结构
  4. 增删改查用链式 API:Insertable / Updateable / Deleteable / Queryable
  5. 列表查询用 ToPageList(pageIndex, pageSize, ref total) 分页

工作流二:接数据库现成表(DB First)

  1. 用 db.DbFirst 系列方法按表生成实体类
  2. 需要改映射时在生成结果上加 [SugarColumn(ColumnName=...)] 调整
  3. 查询照常走链式 API,不写 SQL

工作流三:上生产前的高可用配置

  1. 读写分离:配 SlaveConnectionConfigs,写主读从
  2. 大表按时间分表:标 [SplitTable],查询时用分表 API
  3. 打开 AOP:db.Aop.OnLogExecuting 异步落日志,接慢 SQL 监控
  4. 百万级导入改用 Insertable(list).UseSqlBulkCopy(),并确认目标库支持批量协议

常见问题

问题解决
表名映射不对[SugarTable("name")] 显式指定实体对应的表名
导航属性查不到数据Includes 需要配合 Mapper 显式配置映射关系,否则不会自动联表
并发下报连接已关闭 / 数据错乱SqlSugarClient 非线程安全,多线程与 DI 场景改用 SqlSugarScope
中文乱码MySQL 用 utf8mb4,连接字符串加 Charset=utf8mb4,列与库排序规则一并设为 utf8mb4
时间精度丢失列改 datetime(3)(MySQL)或 datetime2(SQL Server)
Code First 报 InitTables 无效数据库未建或用错库:先 DbMaintenance.CreateDatabase(),再 CodeFirst.InitTables<T>()

AI 使用建议

推荐工作流

  1. 创建客户端:DI 注入用 SqlSugarScope(线程安全),单次使用用 SqlSugarClient(记得 IsAutoCloseConnection = true)
  2. 定义实体:[SugarTable("表名")] + [SugarColumn(IsPrimaryKey = true)] 标注特性
  3. Code First 建表:db.CodeFirst.InitTables<T>() 自动创建/更新表结构
  4. CRUD:Insertable/Updateable/Deleteable/Queryable 链式 API
  5. 高级特性:读写分离(SlaveConnectionConfigs)、分表([SplitTable])、AOP 日志(db.Aop.OnLogExecuting)

关键模式与常见陷阱

  • 线程安全:多线程场景务必用 SqlSugarScope(内部连接池),SqlSugarClient 非线程安全
  • 实体特性:主键用 [SugarColumn(IsPrimaryKey = true)],自增用 IsIdentity = true,雪花 ID 不要设 IsIdentity
  • 批量操作:大批量插入用 Insertable(list).UseSqlBulkCopy() 比逐条快 10-100 倍
  • 分页查询:用 ToPageList(pageIndex, pageSize, ref total) 而不是 ToList() 后手动分页
  • 中文乱码:MySQL 连接字符串加 Charset=utf8mb4,列类型用 utf8mb4
  • AOP 最佳实践:OnLogExecuting 异步写日志,避免阻塞主查询流程

如何选择正确方案

场景推荐方案
新项目快速开发SqlSugar(Code First + 链式查询)
政企项目(达梦/金仓)SqlSugar 或 SOD(两者都支持国产库)
已有数据库(DB First)SqlSugar(自动生成实体)
高性能批量处理SqlSugar + SqlBulkCopy
MyBatis 风格 XMLSOD SQL-MAP

相关技能


参考资源

Frequently asked questions

What does the Sqlsugar AI skill do?

Use when doing multi-database ORM operations in .NET — SqlSugarClient/SqlSugarScope, Queryable<T> chain queries, ToPageList paging, Insertable/Updateable bulk, CodeFirst.InitTables, [SplitTable] sharding, slave connection config. Also for table-name mapping mismatches, unsafe shared SqlSugarClient across threads, and MySQL utf8mb4 mojibake. SqlSugar: .NET ORM for 10+ databases.

Why use Sqlsugar on TypingMind?

Because you install it once and use it with any model. Sqlsugar is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Sqlsugar in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/znlgis/opengis-skills/tree/main/csharp/sqlsugar. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Sqlsugar?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Sqlsugar?

As many as you like. As long as a model supports skills, you can use Sqlsugar with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Sqlsugar AI skill free?

Yes. It is published on GitHub by znlgis under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇