SqlSugar 简介
安装 SqlSugar
配置数据库连接
csharp
// 创建 SqlSugarClient 实例
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "Server=服务器地址;Database=数据库名;Uid=用户名;Pwd=密码;",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
基本的 CRUD 操作
创建(Create)
csharp
var student = new Student() { Name = "张三", Age = 20 };
int id = db.Insertable(student).ExecuteReturnIdentity();
读取(Read)
csharp
var students = db.Queryable<Student>().ToList();
更新(Update)
csharp
var student = db.Queryable<Student>().First(it => it.Id == 1);
student.Age = 21;
db.Updateable(student).ExecuteCommand();
删除(Delete)
csharp
db.Deleteable<Student>(it => it.Id == 1).ExecuteCommand();
使用实体类
csharp
[SugarTable("Student")]
public class Student
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
复杂查询
csharp
var list = db.Queryable<Student, School, (int)(studentId, schoolId) => (student.Id, school.SchoolId))
.Where((student, school) => student.SchoolId == school.Id)
.ToList();
事务处理
csharp
db.Ado.UseTran(() =>
{
db.Insertable(new Student() { Name = "李四", Age = 19 }).ExecuteCommand();
db.Insertable(new Student() { Name = "王五", Age = 18 }).ExecuteCommand();
throw new Exception("出错了,回滚");
});
结论
往期精品推荐: