SqlSugar小技巧 - 删除数据

SqlSugar 是一款 老牌 .NET 开源ORM框架,由果糖大数据科技团队维护和更新 ,开箱即用最易上手的ORM框架 。生态圈丰富,目前开源生态仅次于微软的EF Core。文章主要记录一些使用SqlSugar删除数据的小技巧

1 实体删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//单个实体删除
db.Deleteable<StudentInfo>().Where(new StudentInfo() { Id = 1 }).ExecuteCommand();

//List<实体> 删除集合
List<StudentInfo> list = new List<StudentInfo>()
{
new StudentInfo() { Id = 2 },
new StudentInfo() { Id = 3 }
};
db.Deleteable<StudentInfo>(list).ExecuteCommandHasChange(); //批量删除

//根据主键删除
db.Deleteable<StudentInfo>().In(4).ExecuteCommand();

//无主键删除
db.Deleteable<StudentInfo>().In(it => it.Id, 5).ExecuteCommand();

//根据主键数组删除
db.Deleteable<StudentInfo>().In(new int[] { 6, 7 }).ExecuteCommand();

//无主键数组删除
db.Deleteable<StudentInfo>().In(it => it.Id, new int[] { 8, 9 }).ExecuteCommand();

//表达式删除
db.Deleteable<StudentInfo>().Where(it => it.Id == 10).ExecuteCommand();

2 无实体删除

只更新修改字段
1
2
3
4
5
6
7
8
9
db.Deleteable<object>()
.AS("[StudentInfo]")
.Where("id=@id", new { id = 11 })
.ExecuteCommand();

db.Deleteable<object>()
.AS("[StudentInfo]")
.Where("id in (@id) ", new { id = new int[] { 12, 13, 14 } })
.ExecuteCommand();//批量

3 根据字典集合删除

1
2
3
4
5
6
7
8
9
10
11
Dictionary<string, object> parameter = new Dictionary<string, object>();
parameter.Add("Id", 15);
List<Dictionary<string, object>> dic = new List<Dictionary<string, object>>()
{
parameter
};

db.Deleteable<object>()
.AS("[StudentInfo]")
.WhereColumns(dic)
.ExecuteCommand();