SqlSugar ORM 基础使用教程

1. 简介

SqlSugar 是一款轻量级、高性能的国产 ORM 框架,支持主流数据库(MySQL/SQL Server/Oracle/PostgreSQL等),具有以下特点:

  • 简单易用的 Lambda 表达式查询

  • 强大的分库分表支持

  • 完善的 Code First 开发体验

  • 高性能(官方基准测试优于大部分主流ORM)

  • 支持 .NET Framework 4.6+ 和 .NET Core 2.0+

2. 环境准备

2.1 安装

通过 NuGet 包管理器安装:

Install-Package SqlSugar
 
  

2.2 数据库准备

以 MySQL 为例,创建示例数据库:

CREATE DATABASE SampleDB;
USE SampleDB;

CREATE TABLE Users (
    Id INT PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(50) NOT NULL,
    Age INT,
    CreateTime DATETIME DEFAULT CURRENT_TIMESTAMP
);

3. 基础配置

3.1 创建实体类

[SugarTable("Users")]
public class User
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public int Id { get; set; }
    
    [SugarColumn(Length = 50)]
    public string Name { get; set; }
    
    public int? Age { get; set; }
    
    [SugarColumn(IsNullable = true)]
    public DateTime CreateTime { get; set; }
}

3.2 实体配置-配置SugarColumn属性
在 SqlSugar 中,SugarColumn 属性用于配置列的元数据信息,这对于 ORM 映射非常重要。下面是一些常见的 SugarColumn 属性及其用途:

1、ColumnName-指定数据库表中对应的列名。
2、IsNullable-指定列是否可以为 NULL。
3、IsIdentity-指定列是否为自增列。
4、IsPrimaryKey-指定列是否为主键。
5、DbType-指定列的数据类型。
6、Length-指定列的最大长度。
7、CSharpType-指定 C# 中的类型
8、IsIgnore-指定是否忽略此属性
9、DefaultValue-指定默认值

3.3 初始化SqlSugarClient

public class DbContext
{
    public static SqlSugarClient GetInstance()
    {
        return new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = "Server=localhost;Database=SampleDB;Uid=root;Pwd=123456;",
            DbType = DbType.MySql,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });
    }
}

4. 基础CRUD操作

4.1 插入数据

using var db = DbContext.GetInstance();

// 插入单条
var user = new User { Name = "张三", Age = 25 };
int id = db.Insertable(user).ExecuteReturnIdentity();

// 批量插入
var users = new List
{
    new User { Name = "李四", Age = 30 },
    new User { Name = "王五", Age = 28 }
};
db.Insertable(users).ExecuteCommand();
 
  

4.2 查询数据

// 查询所有
var list = db.Queryable().ToList();

// 条件查询
var user = db.Queryable()
            .Where(u => u.Age > 25)
            .First();

// 分页查询
var pageList = db.Queryable()
                .Where(u => u.Age > 20)
                .ToPageList(1, 10, ref totalCount);
 
  

4.3 更新数据

// 更新整个实体
user.Name = "修改后的名字";
db.Updateable(user).ExecuteCommand();

// 条件更新
db.Updateable()
  .SetColumns(u => u.Age == 30)
  .Where(u => u.Id == 1)
  .ExecuteCommand();
 
  

4.4 删除数据

// 根据主键删除
db.Deleteable(1).ExecuteCommand();

// 条件删除
db.Deleteable()
  .Where(u => u.Age < 18)
  .ExecuteCommand();
 
  

5. 事务处理

try
{
    db.Ado.BeginTran();
    
    // 业务操作1
    db.Insertable(user1).ExecuteCommand();
    
    // 业务操作2
    db.Updateable(user2).ExecuteCommand();
    
    db.Ado.CommitTran();
}
catch(Exception ex)
{
    db.Ado.RollbackTran();
    throw;
}
 
  

6. 高级功能示例

6.1 联表查询

var query = db.Queryable((u, o) => u.Id == o.UserId)
            .Where((u, o) => u.Age > 25)
            .Select((u, o) => new
            {
                UserName = u.Name,
                OrderNo = o.OrderNumber
            })
            .ToList();
 
  

7. 最佳实践

7.1 性能优化

  • 批量操作使用Insertable(list).ExecuteCommand()代替循环插入

  • 频繁查询的字段添加索引

  • 使用AsQueryable()延迟查询

7.2 代码规范

  • 实体类使用[SugarTable][SugarColumn]显式配置

  • 复杂查询使用Lambda表达式保持强类型

  • 事务范围尽量缩小

7.3 常见问题

  1. 日期格式问题
    配置MySql全局日期格式:

    db.Ado.ExecuteCommand("SET GLOBAL sql_mode='STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION';");
     
  2. 导航属性加载
    使用Mapper方法实现:

    var user = db.Queryable()
                .Mapper(u => u.Orders, u => u.Id)
                .First();
     

8. 扩展阅读

  • 官方文档:SqlSugar .Net ORM 5.X 官网 、文档、教程 - SqlSugar 5x - .NET果糖网

  • GitHub仓库:https://github.com/donet5/SqlSugar

你可能感兴趣的:(c#)