五.SQLSugar

27 次查看
# SQLSugar
SQLSugar 是一个轻量级的 ORM(对象关系映射)框架,用于 .NET 平台,支持多种数据库。
## 1. 安装 SQLSugar
nuget搜索sqlsugar进行安装,.net framework安装sqlsugar,.net core安装sqlsugar core。
![](https://www.diandiandidi.club:12346/api/note/getImage/9/b96bdc33-740f-46e4-878a-9b25a90c0512-.png)
## 2.基础配置
### 2.1 连接配置

```c#
var db = new SqlSugarScope(new ConnectionConfig()
{
    ConnectionString = "Server=.;Database=Test;User ID=sa;Password=123456;",
    DbType = DbType.SqlServer,  // 数据库类型
    IsAutoCloseConnection = true, // 自动释放
    ConfigureExternalServices = new ConfigureExternalServices()
    {
        EntityService = (c, p) => 
        {
            p.IsIgnore = p.PropertyName == "IgnoreField"; // 全局忽略字段
        }
    }
});
```

### 2.2 多租户配置 *

```c#
var db = new SqlSugarScope(new List<ConnectionConfig>()
{
    new ConnectionConfig(){ ConfigId="Order", DbType=DbType.SqlServer, ConnectionString=..},
    new ConnectionConfig(){ ConfigId="User", DbType=DbType.MySql, ConnectionString=..}
});
```

## 3.实体映射
### 3.1 基础特性

```c#
[SugarTable("Student", "学生表")] // 表名和描述
public class Student
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public int Id { get; set; }
    
    [SugarColumn(ColumnName = "stu_name", ColumnDescription = "姓名")]
    public string Name { get; set; }
    
    [SugarColumn(IsNullable = false, ColumnDataType = "nvarchar(50)")]
    public string Address { get; set; }
    
    [SugarColumn(IsIgnore = true)] // 忽略映射
    public string TempData { get; set; }
    
    [SugarColumn(IsOnlyIgnoreInsert = true)] // 仅插入时忽略
    public DateTime? UpdateTime { get; set; }
    
    [SugarColumn(IsOnlyIgnoreUpdate = true)] // 仅更新时忽略
    public DateTime CreateTime { get; set; }
}
```

### 3.2 复杂类型映射

```c#
[SugarTable("Order")]
public class Order
{
    [SugarColumn(IsJson = true)] // JSON序列化
    public List<OrderItem> Items { get; set; }
    
    [SugarColumn(ColumnDataType = "varchar(max)")] // 长文本
    public string Remark { get; set; }
}
```

## 4.CRUD操作
### 4.1 查询操作

```c#
// 基础查询
var list = db.Queryable<Student>().ToList();

// 条件查询
var student = db.Queryable<Student>()
               .Where(s => s.Age > 18)
               .First();

// 动态条件
Expression<Func<Student, bool>> exp = s => s.Id > 0;
if(condition) exp = exp.And(s => s.Name.Contains("张"));

// 分页查询
var page = db.Queryable<Student>()
            .Where(s => s.Age > 18)
            .ToPageList(pageIndex, pageSize, ref total);

// 联表查询
var result = db.Queryable<Student, StudentClass>((s, c) => s.ClassId == c.Id)
              .Select((s, c) => new { s.Name, StudentClassName = c.Name })
              .ToList();
```

### 4.2 插入操作

```c#
// 单条插入
var id = db.Insertable(new Student{ Name="张三" }).ExecuteReturnIdentity();

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

// 插入并排除列
db.Insertable(entity).IgnoreColumns(s => new { s.CreateTime }).ExecuteCommand();
```

### 4.3 更新操作

```c#
// 根据主键更新
db.Updateable(student).ExecuteCommand();

// 条件更新
db.Updateable<Student>()
  .SetColumns(s => s.Name == "李四")
  .Where(s => s.Id == 1)
  .ExecuteCommand();

// 更新指定列
db.Updateable(student)
  .UpdateColumns(s => new { s.Name, s.Age })
  .ExecuteCommand();
```

### 4.4 删除操作

```c#
// 主键删除
db.Deleteable<Student>(1).ExecuteCommand();

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

// 假删除
db.Updateable<Student>()
  .SetColumns(s => s.IsDeleted == true)
  .Where(s => s.Id == 1)
  .ExecuteCommand();
```

## 5.高级功能
### 5.1 事务处理

```c#
try
{
    db.Ado.BeginTran();
    
    // 业务操作
    db.Insertable(entity1).ExecuteCommand();
    db.Updateable(entity2).ExecuteCommand();
    
    db.Ado.CommitTran();
}
catch(Exception ex)
{
    db.Ado.RollbackTran();
    throw;
}
```

### 5.2 AOP拦截

```c#
var db = new SqlSugarScope(new ConnectionConfig()
{
    // 配置...
},
services => 
{
    services.Aop.OnLogExecuting = (sql, pars) => 
    {
        Console.WriteLine(sql); // 打印SQL
    };
    
    services.Aop.OnError = exp => 
    {
        // 错误处理
    };
});
```

## 6.代码生成
### 6.1 生成实体类

```c#
// 生成所有表
db.DbFirst.IsCreateAttribute().CreateClassFile("实体类路径", "命名空间");

// 生成指定表
db.DbFirst.Where("TableName='Student'").CreateClassFile("路径", "命名空间");
```

### 6.2 生成数据库

```c#
// 根据实体创建表
db.CodeFirst.InitTables(typeof(Student), typeof(StudentClass));

// 同步结构
db.CodeFirst.SyncStructure(typeof(Student));
```

## 7.提示
### 7.1 动态表名

```c#
// 按日期分表
var tableName = $"Order_{DateTime.Now:yyyyMM}";
var list = db.Queryable<Order>().AS(tableName).ToList();
```

### 7.2 批量操作

```c#
// 批量更新
db.Updateable(list).ExecuteCommand();

// 批量删除
db.Deleteable(list).ExecuteCommand();
```

### 7.3 复杂SQL

```c#
// 原生SQL查询
var list = db.Ado.SqlQuery<Student>("SELECT * FROM Student WHERE Age>@age", 
              new { age = 18 });
```

### 7.4 SqlSugarScope和SqlSugarClient区别
SqlSugarClient​每次实例化​​都会创建新的数据库连接,需要手动管理连接生命周期。

SqlSugarScope单例模式​​设计,整个应用生命周期只需实例化一次。

© 2026 XyzRgb.space · 本页内容为个人学习记录,如有错漏欢迎指正。