SqlSugar 文档
第一部分:SqlSugar 基础入门
1.1 SqlSugar 简介
SqlSugar 是一款国产的轻量级、高性能 ORM 框架,具有以下特点:
主要优势:
-
性能接近原生 ADO.NET
-
语法简洁直观,学习成本低
-
完善的文档和活跃的社区支持
-
支持多种数据库
-
强大的代码生成和迁移功能
1.2 环境准备与安装
创建项目
cs
dotnet new console -n SqlSugarDemo
cd SqlSugarDemo
安装 SqlSugar
cs
# 使用 NuGet 安装
Install-Package SqlSugar
# 或者使用 .NET CLI
dotnet add package SqlSugar
安装数据库驱动(根据使用的数据库选择)
cs
# SQL Server
Install-Package Microsoft.Data.SqlClient
# MySQL
Install-Package MySqlConnector
# PostgreSQL
Install-Package Npgsql
# SQLite
Install-Package Microsoft.Data.Sqlite
1.3 基础配置
创建数据库连接配置
cs
using SqlSugar;
public class DatabaseConfig
{
public static SqlSugarScope GetDatabase()
{
return new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = "Server=.;Database=TestDB;Trusted_Connection=true;",
DbType = DbType.SqlServer, // 数据库类型
IsAutoCloseConnection = true, // 自动释放
InitKeyType = InitKeyType.Attribute // 从实体特性读取主键信息
});
}
}
多数据库配置示例
cs
public static SqlSugarScope CreateMultiDatabase()
{
return new SqlSugarScope(new ConnectionConfig()
{
// 主数据库
ConnectionString = "Server=.;Database=MasterDB;Trusted_Connection=true;",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
// 从数据库配置
SlaveConnectionConfigs = new List<SlaveConnectionConfig>()
{
new SlaveConnectionConfig()
{
HitRate = 10, // 权重
ConnectionString = "Server=.;Database=SlaveDB1;Trusted_Connection=true;"
}
}
});
}
第二部分:实体类与数据模型
2.1 实体类定义
基础实体类
cs
[SugarTable("Students")] // 指定表名
public class Student
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
[SugarColumn(Length = 50, ColumnDescription = "学生姓名")]
public string Name { get; set; }
[SugarColumn(ColumnDataType = "int")]
public int Age { get; set; }
[SugarColumn(IsNullable = true, Length = 100)]
public string Email { get; set; }
[SugarColumn(IsIgnore = true)] // 忽略映射
public string DisplayName => $"{Name}({Age})";
[SugarColumn(IsOnlyIgnoreInsert = true)] // 仅插入时忽略
public DateTime? UpdateTime { get; set; }
}
复杂实体关系
cs
[SugarTable("Classes")]
public class Class
{
[SugarColumn(IsPrimaryKey = true)]
public int Id { get; set; }
[SugarColumn(Length = 50)]
public string ClassName { get; set; }
[Navigate(NavigateType.OneToMany, nameof(Student.ClassId))]
public List<Student> Students { get; set; }
}
[SugarTable("Courses")]
public class Course
{
[SugarColumn(IsPrimaryKey = true)]
public int Id { get; set; }
[SugarColumn(Length = 100)]
public string CourseName { get; set; }
[SugarColumn(ColumnDataType = "decimal(18,2)")]
public decimal Credit { get; set; }
}
// 多对多关系中间表
[SugarTable("StudentCourses")]
public class StudentCourse
{
[SugarColumn(IsPrimaryKey = true)]
public int Id { get; set; }
public int StudentId { get; set; }
public int CourseId { get; set; }
[SugarColumn(IsNullable = true)]
public decimal? Score { get; set; }
}
2.2 数据库上下文
cs
public class SchoolContext
{
public SqlSugarScope Db { get; }
public SchoolContext()
{
Db = new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = "Server=.;Database=SchoolDB;Trusted_Connection=true;",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
ConfigureExternalServices = new ConfigureExternalServices()
{
EntityService = (property, column) =>
{
// 全局配置:所有 string 类型默认长度为 255
if (property.PropertyType == typeof(string) && column.DataType == "varchar")
{
column.Length = 255;
}
}
}
});
// 输出 SQL 日志
Db.Aop.OnLogExecuting = (sql, paras) =>
{
Console.WriteLine($"SQL: {sql}");
if (paras != null)
{
foreach (var param in paras)
{
Console.WriteLine($"Parameter: {param.ParameterName} = {param.Value}");
}
}
};
}
// 实体集合
public SimpleClient<Student> Students => new SimpleClient<Student>(Db);
public SimpleClient<Class> Classes => new SimpleClient<Class>(Db);
public SimpleClient<Course> Courses => new SimpleClient<Course>(Db);
}
第三部分:基础 CRUD 操作
3.1 插入操作
cs
public class StudentService
{
private readonly SqlSugarScope _db;
public StudentService(SqlSugarScope db)
{
_db = db;
}
// 插入单个实体
public int AddStudent(Student student)
{
return _db.Insertable(student).ExecuteCommand();
}
// 插入并返回自增ID
public int AddStudentReturnId(Student student)
{
return _db.Insertable(student).ExecuteReturnIdentity();
}
// 批量插入
public bool BatchAddStudents(List<Student> students)
{
return _db.Insertable(students).ExecuteCommand() > 0;
}
// 插入或更新
public void InsertOrUpdate(Student student)
{
_db.Storageable(student).ExecuteCommand();
}
}
3.2 查询操作
cs
public class QueryService
{
private readonly SqlSugarScope _db;
public QueryService(SqlSugarScope db)
{
_db = db;
}
// 基础查询
public List<Student> GetAllStudents()
{
return _db.Queryable<Student>().ToList();
}
// 条件查询
public List<Student> GetStudentsByAge(int minAge, int maxAge)
{
return _db.Queryable<Student>()
.Where(s => s.Age >= minAge && s.Age <= maxAge)
.ToList();
}
// 排序查询
public List<Student> GetStudentsOrdered()
{
return _db.Queryable<Student>()
.OrderBy(s => s.Age, OrderByType.Desc)
.OrderBy(s => s.Name, OrderByType.Asc)
.ToList();
}
// 分页查询
public (List<Student>, int) GetStudentsPaged(int pageIndex, int pageSize)
{
var total = 0;
var list = _db.Queryable<Student>()
.ToPageList(pageIndex, pageSize, ref total);
return (list, total);
}
// 选择特定字段
public List<dynamic> GetStudentNames()
{
return _db.Queryable<Student>()
.Select(s => new { s.Id, s.Name })
.ToList<dynamic>();
}
}
3.3 更新操作
cs
public class UpdateService
{
private readonly SqlSugarScope _db;
// 更新整个实体
public bool UpdateStudent(Student student)
{
return _db.Updateable(student).ExecuteCommand() > 0;
}
// 只更新特定字段
public bool UpdateStudentAge(int studentId, int newAge)
{
return _db.Updateable<Student>()
.SetColumns(s => s.Age == newAge)
.Where(s => s.Id == studentId)
.ExecuteCommand() > 0;
}
// 批量更新
public bool BatchUpdateStudents(List<Student> students)
{
return _db.Updateable(students).ExecuteCommand() > 0;
}
// 条件更新
public bool UpdateStudentsEmail(string domain)
{
return _db.Updateable<Student>()
.SetColumns(s => s.Email == s.Name + domain)
.Where(s => s.Email == null)
.ExecuteCommand() > 0;
}
}
3.4 删除操作
cs
public class DeleteService
{
private readonly SqlSugarScope _db;
// 根据主键删除
public bool DeleteStudent(int id)
{
return _db.Deleteable<Student>().In(id).ExecuteCommand() > 0;
}
// 条件删除
public bool DeleteStudentsByAge(int maxAge)
{
return _db.Deleteable<Student>()
.Where(s => s.Age > maxAge)
.ExecuteCommand() > 0;
}
// 批量删除
public bool BatchDeleteStudents(List<int> ids)
{
return _db.Deleteable<Student>().In(ids).ExecuteCommand() > 0;
}
// 软删除(需要实体中有 IsDeleted 字段)
public bool SoftDeleteStudent(int id)
{
return _db.Updateable<Student>()
.SetColumns(s => s.IsDeleted == true)
.Where(s => s.Id == id)
.ExecuteCommand() > 0;
}
}
第四部分:高级查询与关联查询
4.1 连表查询
cs
public class JoinQueryService
{
private readonly SqlSugarScope _db;
// 内连接
public List<dynamic> GetStudentWithClass()
{
return _db.Queryable<Student>()
.InnerJoin<Class>((s, c) => s.ClassId == c.Id)
.Select((s, c) => new
{
StudentId = s.Id,
StudentName = s.Name,
ClassName = c.ClassName,
Age = s.Age
})
.ToList<dynamic>();
}
// 左连接
public List<dynamic> GetStudentsWithCourses()
{
return _db.Queryable<Student>()
.LeftJoin<StudentCourse>((s, sc) => s.Id == sc.StudentId)
.LeftJoin<Course>((s, sc, c) => sc.CourseId == c.Id)
.Select((s, sc, c) => new
{
StudentName = s.Name,
CourseName = c.CourseName,
Score = sc.Score
})
.ToList<dynamic>();
}
}
4.2 分组查询
cs
public class GroupQueryService
{
private readonly SqlSugarScope _db;
// 分组统计
public List<dynamic> GetStudentCountByClass()
{
return _db.Queryable<Student>()
.GroupBy(s => s.ClassId)
.Select(s => new
{
ClassId = s.ClassId,
StudentCount = SqlFunc.AggregateCount(s.Id),
AvgAge = SqlFunc.AggregateAvg(s.Age),
MaxAge = SqlFunc.AggregateMax(s.Age),
MinAge = SqlFunc.AggregateMin(s.Age)
})
.ToList<dynamic>();
}
// 分组筛选
public List<dynamic> GetClassesWithManyStudents(int minCount)
{
return _db.Queryable<Student>()
.GroupBy(s => s.ClassId)
.Having(s => SqlFunc.AggregateCount(s.Id) > minCount)
.Select(s => new
{
ClassId = s.ClassId,
StudentCount = SqlFunc.AggregateCount(s.Id)
})
.ToList<dynamic>();
}
}
4.3 子查询
cs
public class SubQueryService
{
private readonly SqlSugarScope _db;
// WHERE 子查询
public List<Student> GetStudentsInPopularClasses()
{
var subQuery = _db.Queryable<Student>()
.GroupBy(s => s.ClassId)
.Having(s => SqlFunc.AggregateCount(s.Id) > 5)
.Select(s => s.ClassId);
return _db.Queryable<Student>()
.Where(s => SqlFunc.Subqueryable(subQuery).Contains(s.ClassId))
.ToList();
}
// SELECT 子查询
public List<dynamic> GetStudentsWithCourseCount()
{
return _db.Queryable<Student>()
.Select(s => new
{
s.Id,
s.Name,
CourseCount = SqlFunc.Subqueryable<StudentCourse>()
.Where(sc => sc.StudentId == s.Id)
.Count()
})
.ToList<dynamic>();
}
}
第五部分:事务与性能优化
5.1 事务处理
cs
public class TransactionService
{
private readonly SqlSugarScope _db;
// 基础事务
public bool TransferCredits(int fromStudentId, int toStudentId, decimal credits)
{
try
{
_db.Ado.BeginTran();
// 操作1:减少学分
_db.Updateable<Student>()
.SetColumns(s => s.Credits == s.Credits - credits)
.Where(s => s.Id == fromStudentId)
.ExecuteCommand();
// 操作2:增加学分
_db.Updateable<Student>()
.SetColumns(s => s.Credits == s.Credits + credits)
.Where(s => s.Id == toStudentId)
.ExecuteCommand();
_db.Ado.CommitTran();
return true;
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
Console.WriteLine($"事务失败: {ex.Message}");
return false;
}
}
// 使用事务特性
[Transactional]
public bool ComplexOperation(Student student, List<Course> courses)
{
_db.Insertable(student).ExecuteCommand();
_db.Insertable(courses).ExecuteCommand();
return true;
}
}
// 事务特性
public class TransactionalAttribute : Attribute
{
public void OnActionExecuting(SqlSugarScope db)
{
db.Ado.BeginTran();
}
public void OnActionExecuted(SqlSugarScope db, bool isSuccess)
{
if (isSuccess)
db.Ado.CommitTran();
else
db.Ado.RollbackTran();
}
}
5.2 性能优化
cs
public class PerformanceService
{
private readonly SqlSugarScope _db;
// 使用读写分离
public List<Student> GetStudentsWithReadSlave()
{
return _db.Queryable<Student>().With(SqlWith.ReadOnly).ToList();
}
// 分页优化
public List<Student> GetStudentsOptimizedPaged(int pageIndex, int pageSize)
{
return _db.Queryable<Student>()
.OrderBy(s => s.Id)
.ToPageList(pageIndex, pageSize);
}
// 使用索引提示
public List<Student> GetStudentsWithIndex()
{
return _db.Queryable<Student>()
.With(SqlWith.Index("IX_Student_Age"))
.Where(s => s.Age > 18)
.ToList();
}
// 批量操作优化
public void BulkInsertStudents(List<Student> students)
{
_db.Fastest<Student>().BulkCopy(students);
}
public void BulkUpdateStudents(List<Student> students)
{
_db.Fastest<Student>().BulkUpdate(students);
}
}
第六部分:实战项目 - 学生管理系统
6.1 项目结构
StudentManagement/
├── Models/ # 数据模型
├── Services/ # 业务服务
├── Repositories/ # 数据访问层
├── Controllers/ # 控制器
└── Program.cs # 主程序
6.2 完整示例
数据模型
cs
// Models/Student.cs
[SugarTable("Students")]
public class Student
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
[SugarColumn(Length = 50)]
public string Name { get; set; }
public int Age { get; set; }
[SugarColumn(Length = 100, IsNullable = true)]
public string Email { get; set; }
public int ClassId { get; set; }
[SugarColumn(ColumnDataType = "decimal(18,2)")]
public decimal Credits { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime? CreateTime { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime? UpdateTime { get; set; }
[Navigate(NavigateType.OneToOne, nameof(ClassId))]
public Class Class { get; set; }
[Navigate(NavigateType.OneToMany, nameof(StudentCourse.StudentId))]
public List<StudentCourse> StudentCourses { get; set; }
}
仓储层
cs
// Repositories/StudentRepository.cs
public class StudentRepository : BaseRepository<Student>
{
public StudentRepository(SqlSugarScope db) : base(db) { }
public List<Student> GetStudentsWithDetails()
{
return _db.Queryable<Student>()
.Includes(s => s.Class)
.Includes(s => s.StudentCourses,
then => then.Includes(sc => sc.Course))
.ToList();
}
public List<Student> SearchStudents(string keyword, int? minAge, int? maxAge)
{
var query = _db.Queryable<Student>();
if (!string.IsNullOrEmpty(keyword))
{
query = query.Where(s => s.Name.Contains(keyword));
}
if (minAge.HasValue)
{
query = query.Where(s => s.Age >= minAge.Value);
}
if (maxAge.HasValue)
{
query = query.Where(s => s.Age <= maxAge.Value);
}
return query.ToList();
}
}
// Repositories/BaseRepository.cs
public class BaseRepository<T> where T : class, new()
{
protected SqlSugarScope _db;
public BaseRepository(SqlSugarScope db)
{
_db = db;
}
public virtual T GetById(int id)
{
return _db.Queryable<T>().InSingle(id);
}
public virtual List<T> GetAll()
{
return _db.Queryable<T>().ToList();
}
public virtual int Add(T entity)
{
return _db.Insertable(entity).ExecuteReturnIdentity();
}
public virtual bool Update(T entity)
{
return _db.Updateable(entity).ExecuteCommand() > 0;
}
public virtual bool Delete(int id)
{
return _db.Deleteable<T>().In(id).ExecuteCommand() > 0;
}
}
业务服务层
cs
// Services/StudentService.cs
public class StudentService
{
private readonly StudentRepository _studentRepo;
private readonly CourseRepository _courseRepo;
public StudentService(StudentRepository studentRepo, CourseRepository courseRepo)
{
_studentRepo = studentRepo;
_courseRepo = courseRepo;
}
public StudentDetailDto GetStudentDetail(int studentId)
{
var student = _studentRepo.GetById(studentId);
if (student == null) return null;
return new StudentDetailDto
{
Id = student.Id,
Name = student.Name,
Age = student.Age,
Email = student.Email,
Credits = student.Credits,
ClassName = student.Class?.ClassName,
Courses = student.StudentCourses?.Select(sc => new CourseDto
{
CourseName = sc.Course?.CourseName,
Credit = sc.Course?.Credit ?? 0,
Score = sc.Score
}).ToList()
};
}
public bool EnrollCourse(int studentId, int courseId)
{
try
{
_db.Ado.BeginTran();
var student = _studentRepo.GetById(studentId);
var course = _courseRepo.GetById(courseId);
if (student == null || course == null)
return false;
var studentCourse = new StudentCourse
{
StudentId = studentId,
CourseId = courseId,
EnrollTime = DateTime.Now
};
_db.Insertable(studentCourse).ExecuteCommand();
_db.Ado.CommitTran();
return true;
}
catch
{
_db.Ado.RollbackTran();
throw;
}
}
}
DTO 类
cs
// Models/DTOs/StudentDetailDto.cs
public class StudentDetailDto
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public decimal Credits { get; set; }
public string ClassName { get; set; }
public List<CourseDto> Courses { get; set; }
}
public class CourseDto
{
public string CourseName { get; set; }
public decimal Credit { get; set; }
public decimal? Score { get; set; }
}
主程序
cs
// Program.cs
class Program
{
static void Main(string[] args)
{
var context = new SchoolContext();
// 初始化数据库
InitializeDatabase(context.Db);
// 运行示例
RunExamples(context.Db);
}
static void InitializeDatabase(SqlSugarScope db)
{
// 创建数据库(如果不存在)
db.DbMaintenance.CreateDatabase();
// 创建表
db.CodeFirst.InitTables<Student, Class, Course, StudentCourse>();
// 初始化数据
InitializeData(db);
}
static void RunExamples(SqlSugarScope db)
{
var studentService = new StudentService(
new StudentRepository(db),
new CourseRepository(db)
);
// 查询学生详情
var student = studentService.GetStudentDetail(1);
Console.WriteLine($"学生: {student.Name}, 班级: {student.ClassName}");
// 搜索学生
var students = studentService.SearchStudents("张", 18, 25);
Console.WriteLine($"找到 {students.Count} 个学生");
}
}
第七部分:SqlSugar 与其他 ORM 框架对比
7.1 性能对比
| 特性 | SqlSugar | Entity Framework Core | Dapper |
|---|---|---|---|
| 查询性能 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 插入性能 | ⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| 批量操作 | ⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐ |
| 内存占用 | ⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ |
7.2 功能特性对比
| 功能 | SqlSugar | EF Core | Dapper |
|---|---|---|---|
| Code First | ✅ 优秀 | ✅ 优秀 | ❌ 不支持 |
| Db First | ✅ 优秀 | ✅ 良好 | ❌ 不支持 |
| 迁移功能 | ✅ 良好 | ✅ 优秀 | ❌ 不支持 |
| LINQ 支持 | ✅ 优秀 | ✅ 优秀 | ⚠️ 有限 |
| 事务处理 | ✅ 优秀 | ✅ 优秀 | ✅ 优秀 |
| 读写分离 | ✅ 内置 | ⚠️ 需要扩展 | ⚠️ 需要扩展 |
| 多数据库 | ✅ 优秀 | ✅ 良好 | ✅ 优秀 |
| 中文文档 | ✅ 完善 | ⚠️ 英文为主 | ⚠️ 英文为主 |
7.3 学习成本对比
| 方面 | SqlSugar | EF Core | Dapper |
|---|---|---|---|
| 学习曲线 | ⭐⭐ 平缓 | ⭐⭐⭐⭐ 陡峭 | ⭐ 简单 |
| 配置复杂度 | ⭐⭐ 简单 | ⭐⭐⭐⭐ 复杂 | ⭐ 简单 |
| 调试友好度 | ⭐⭐⭐⭐ 良好 | ⭐⭐⭐ 一般 | ⭐⭐⭐⭐⭐ 优秀 |
| 社区支持 | ⭐⭐⭐⭐ 活跃 | ⭐⭐⭐⭐⭐ 非常活跃 | ⭐⭐⭐⭐ 活跃 |
7.4 适用场景
SqlSugar 适用场景:
-
需要高性能的读写操作
-
项目对性能要求较高
-
需要快速开发和简洁的代码
-
国内团队,需要中文文档支持
-
需要多数据库支持
EF Core 适用场景:
-
复杂的业务逻辑和领域模型
-
需要强大的迁移功能
-
团队熟悉微软技术栈
-
需要完整的 ORM 功能
Dapper 适用场景:
-
对性能要求极高
-
简单的 CRUD 操作
-
开发团队熟悉 SQL
-
微服务架构中的轻量级数据访问
7.5 代码风格对比
SqlSugar:
cs
// 语法简洁,类似 LINQ
var list = db.Queryable<Student>()
.Where(s => s.Age > 18)
.OrderBy(s => s.Name)
.ToList();
EF Core:
cs
// 语法简洁,类似 LINQ
var list = db.Queryable<Student>()
.Where(s => s.Age > 18)
.OrderBy(s => s.Name)
.ToList();
Dapper:
cs
// 直接使用 SQL
var list = connection.Query<Student>(
"SELECT * FROM Students WHERE Age > @Age ORDER BY Name",
new { Age = 18 });
第八部分:最佳实践与注意事项
8.1 性能优化建议
-
合理使用索引
-
避免 N+1 查询问题
-
使用分页查询
-
合理使用缓存
-
批量操作代替循环操作
8.2 代码规范
-
使用仓储模式
-
合理分层架构
-
使用 DTO 进行数据传输
-
统一的异常处理
-
完善的日志记录
8.3 常见问题解决
-
连接泄露 :使用
IsAutoCloseConnection = true -
性能问题:使用 AOP 监控 SQL 执行
-
并发冲突:使用乐观锁
-
数据一致性问题:合理使用事务
这个完整的 SqlSugar 教程涵盖了从基础到实战的所有内容,以及与其他 ORM 框架的详细对比,可以帮助你全面掌握 SqlSugar 的使用。