SqlSugar的简单使用

C#中SqlSugar全面使用指南

SqlSugar是一款轻量级的ORM框架,支持多种数据库(SQL Server、MySQL、Oracle、PostgreSQL、SQLite等),具有高性能、易用性好的特点。下面是对SqlSugar基本使用方法的全面整理。

1. 安装与配置

安装

通过NuGet安装:

bash 复制代码
Install-Package SqlSugar

基础配置

csharp 复制代码
// 创建SqlSugarClient实例
var db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = "server=.;database=TestDB;uid=sa;pwd=123456",
    DbType = DbType.SqlServer, // 设置数据库类型
    IsAutoCloseConnection = true, // 自动关闭连接
    InitKeyType = InitKeyType.Attribute // 从实体特性中读取主键和自增列信息
});

// 依赖注入方式(ASP.NET Core)
services.AddScoped<ISqlSugarClient>(implementationFactory =>
{
    return new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = configuration.GetConnectionString("DefaultConnection"),
        DbType = DbType.SqlServer,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
});

2. 实体类定义

csharp 复制代码
[SugarTable("Student")] // 指定表名
public class Student
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] // 主键、自增
    public int Id { get; set; }
    
    [SugarColumn(ColumnName = "Name")] // 指定列名
    public string Name { get; set; }
    
    public int Age { get; set; }
    
    public string Class { get; set; }
    
    [SugarColumn(IsNullable = true)] // 允许为空
    public string Remark { get; set; }
}

3. 基本CRUD操作

插入数据

csharp 复制代码
// 单条插入
var student = new Student { Name = "张三", Age = 18, Class = "一班" };
var insertId = db.Insertable(student).ExecuteReturnIdentity(); // 返回自增ID

// 批量插入
var students = new List<Student>() {
    new Student { Name = "李四", Age = 19, Class = "二班" },
    new Student { Name = "王五", Age = 20, Class = "三班" }
};
var result = db.Insertable(students).ExecuteCommand(); // 返回受影响行数

查询数据

csharp 复制代码
// 查询所有
var allStudents = db.Queryable<Student>().ToList();

// 根据ID查询
var student = db.Queryable<Student>().InSingle(1); // 主键查询
var student = db.Queryable<Student>().Where(s => s.Id == 1).First();

// 条件查询
var students = db.Queryable<Student>()
    .Where(s => s.Age > 18 && s.Class == "一班")
    .ToList();

// 指定字段查询
var names = db.Queryable<Student>()
    .Select(s => new { s.Name, s.Age }) // 匿名类型
    .Where(s => s.Age > 18)
    .ToList();

更新数据

csharp 复制代码
// 根据主键更新
var student = new Student { Id = 1, Name = "张三修改", Age = 19 };
var result = db.Updateable(student).ExecuteCommand();

// 仅更新指定字段
var result = db.Updateable(student)
    .UpdateColumns(s => new { s.Name, s.Age }) // 只更新Name和Age字段
    .ExecuteCommand();

// 条件更新
var result = db.Updateable<Student>()
    .SetColumns(s => new Student() { Age = s.Age + 1 }) // 年龄+1
    .Where(s => s.Class == "一班")
    .ExecuteCommand();

删除数据

csharp 复制代码
// 根据主键删除
var result = db.Deleteable<Student>().In(1).ExecuteCommand();

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

4. 高级查询功能

复杂条件与排序

csharp 复制代码
var students = db.Queryable<Student>()
    .Where(s => s.Age > 18)
    .Where(s => s.Class.In(new string[] { "一班", "二班" }))
    .Where(s => s.Name.Contains("张")) // 模糊查询
    .OrderBy(s => s.Age) // 升序
    .OrderByDescending(s => s.Id) // 降序
    .ToList();

分组查询

csharp 复制代码
var groupResult = db.Queryable<Student>()
    .GroupBy(s => s.Class)
    .Select(s => new { 
        ClassName = s.Class,
        Count = SqlFunc.AggregateCount(s.Id),
        AvgAge = SqlFunc.AggregateAvg(s.Age)
    })
    .ToList();

动态查询

csharp 复制代码
IQueryable<Student> query = db.Queryable<Student>();
if (!string.IsNullOrEmpty(className))
{
    query = query.Where(s => s.Class == className);
}
if (minAge.HasValue)
{
    query = query.Where(s => s.Age >= minAge.Value);
}
var students = query.ToList();

5. 事务处理

csharp 复制代码
// 手动事务
try
{
    db.Ado.BeginTran(); // 开始事务
    
    db.Insertable(new Student { Name = "赵六", Age = 21, Class = "四班" }).ExecuteCommand();
    db.Updateable<Student>()
        .SetColumns(s => new Student { Age = 22 })
        .Where(s => s.Name == "张三")
        .ExecuteCommand();
    
    db.Ado.CommitTran(); // 提交事务
}
catch (Exception ex)
{
    db.Ado.RollbackTran(); // 回滚事务
    throw;
}

// 简化事务
db.Ado.Transaction(() =>
{
    db.Insertable(new Student { Name = "赵六", Age = 21, Class = "四班" }).ExecuteCommand();
    db.Updateable<Student>()
        .SetColumns(s => new Student { Age = 22 })
        .Where(s => s.Name == "张三")
        .ExecuteCommand();
});

6. 多表查询与连接

内连接

csharp 复制代码
var result = db.Queryable<Student, School>((s, sch) => new JoinQueryInfos(
        JoinType.Inner, s.SchoolId == sch.Id // 关联条件
    ))
    .Where((s, sch) => s.Age > 18)
    .Select((s, sch) => new { 
        StudentName = s.Name,
        SchoolName = sch.Name,
        s.Age
    })
    .ToList();

多表连接与子查询

csharp 复制代码
// 多表连接
var result = db.Queryable<Student, School, Teacher>((s, sch, t) => new JoinQueryInfos(
        JoinType.Inner, s.SchoolId == sch.Id,
        JoinType.Left, s.TeacherId == t.Id
    ))
    .Select((s, sch, t) => new { 
        StudentName = s.Name,
        SchoolName = sch.Name,
        TeacherName = t.Name
    })
    .ToList();

// 子查询
var subQuery = db.Queryable<Teacher>().Where(t => t.Age > 40).Select(t => t.Id);
var students = db.Queryable<Student>()
    .Where(s => subQuery.Contains(s.TeacherId))
    .ToList();

7. 分页查询

csharp 复制代码
int pageIndex = 1;
int pageSize = 10;

// 基本分页
var pageResult = db.Queryable<Student>()
    .Where(s => s.Age > 18)
    .OrderBy(s => s.Id)
    .ToPageList(pageIndex, pageSize);

// 分页且获取总记录数
RefAsync<int> totalCount = 0;
var pageResult = db.Queryable<Student>()
    .Where(s => s.Age > 18)
    .OrderBy(s => s.Id)
    .ToPageList(pageIndex, pageSize, totalCount);
Console.WriteLine($"总记录数: {totalCount}");

8. 批量操作

高性能批量插入

csharp 复制代码
var students = new List<Student> { /* 初始化数据 */ };

// 普通批量插入
db.Insertable(students).ExecuteCommand();

// 使用BulkCopy (SQL Server)
db.Fastest<Student>().BulkInsert(students);

// 批量插入并返回自增ID
var insertResult = db.Insertable(students).ExecuteReturnEntityList();

批量更新/删除

csharp 复制代码
// 批量更新
db.Updateable(students).ExecuteCommand();

// 批量更新指定列
db.Updateable(students)
    .UpdateColumns(s => new { s.Name }) // 只更新Name列
    .ExecuteCommand();

// 批量删除
var ids = new int[] { 1, 2, 3 };
db.Deleteable<Student>().In(ids).ExecuteCommand();

9. AOP功能

全局过滤器

csharp 复制代码
// 软删除过滤器
db.QueryFilter.AddTableFilter<IDeleteFilter>("IsDeleted", false);

public interface IDeleteFilter
{
    bool IsDeleted { get; set; }
}

[SugarTable("Student")]
public class Student : IDeleteFilter
{
    // 其他属性
    public bool IsDeleted { get; set; }
}

操作拦截

csharp 复制代码
// SQL执行前
db.Aop.OnLogExecuting = (sql, pars) => 
{
    Console.WriteLine($"执行SQL: {sql}");
};

// SQL执行后
db.Aop.OnLogExecuted = (sql, time) => 
{
    Console.WriteLine($"执行时间: {time}ms");
};

// 错误处理
db.Aop.OnError = (exp) => 
{
    // 记录错误日志
};

10. 其他实用功能

原生SQL操作

csharp 复制代码
// 查询返回实体
var students = db.Ado.SqlQuery<Student>("SELECT * FROM Student WHERE Age > @age", new { age = 18 });

// 执行命令
db.Ado.ExecuteCommand("UPDATE Student SET Age = Age + 1 WHERE Class = @class", new { class = "一班" });

// 返回DataTable
var dataTable = db.Ado.GetDataTable("SELECT * FROM Student");

代码优先与数据库迁移

csharp 复制代码
// 创建表
db.DbMaintenance.CreateTable(typeof(Student));

// 更新表结构
db.DbMaintenance.UpdateTable<Student>();

// 生成实体类
db.DbFirst.Context.InitKeyType = InitKeyType.Attribute;
db.DbFirst.Where(tableName: "Student").CreateClassFile("Student.cs", "Models");

读写分离

csharp 复制代码
var config = new ConnectionConfig()
{
    ConnectionString = "主库连接字符串",
    SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {
        new SlaveConnectionConfig() { ConnectionString = "从库1连接字符串" },
        new SlaveConnectionConfig() { ConnectionString = "从库2连接字符串" }
    },
    DbType = DbType.SqlServer,
    IsAutoCloseConnection = true,
    SlaveConnectionPool = true
};

var db = new SqlSugarClient(config);

// 查询自动使用从库,写操作使用主库
var students = db.Queryable<Student>().ToList(); // 从库查询
db.Insertable(new Student() { /* ... */ }).ExecuteCommand(); // 主库写入

总结

SqlSugar作为一款优秀的ORM框架,提供了丰富的功能和简洁的API,能极大提高开发效率。以上涵盖了SqlSugar的核心功能,包括基本CRUD、高级查询、事务处理、多表连接、分页、批量操作、AOP等。在实际应用中,可根据项目需求选择适合的功能,合理使用可以显著提升数据访问层的开发效率和代码质量。

注意:以上代码示例需要根据实际数据库结构和业务需求进行调整,特别是连接字符串和表字段映射部分。

相关推荐
dotent·16 小时前
C#基于WPF UI框架的通用基础上位机测试WPF框架
ui·c#·wpf
合作小小程序员小小店16 小时前
桌面开发,超市管理系统开发,基于C#,winform,sql server数据库
开发语言·数据库·sql·microsoft·sqlserver·c#
合作小小程序员小小店18 小时前
桌面开发,在线%超市销售管理%系统,基于vs2022,c#,winform,sql server数据
开发语言·数据库·microsoft·c#
p***323520 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
2501_9418072621 小时前
Java高性能消息队列与Kafka实战分享:大规模消息处理、异步通信与性能优化经验
c#·linq
周杰伦fans1 天前
C# 中的**享元工厂**模式
开发语言·数据库·c#
鹿衔`1 天前
通过Flink 1.19 客户端实现Flink集群连接 Kafka 基础测试报告
c#·linq
玩泥巴的1 天前
.NET 8+ 飞书API实战:自动化群组管理与消息推送
c#·.net·二次开发·飞书