Skip to content
shuxin edited this page May 21, 2023 · 3 revisions

删除数据

Chloe 支持两种数据删除方式。

1. 实体删除:

该方式删除必须要求实体拥有主键,否则会报异常提示。

Person person = new Person();
person.Id = 1;
dbContext.Delete(person);
/*
 * Int32 @P_0 = 1;
   DELETE [Person] WHERE [Person].[Id] = @P_0
 */

2. lambda 方式删除:

使用该方式可以删除单条数据,也可以删除多条数据。

/* 删除单条数据 */
dbContext.Delete<Person>(a => a.Id == 1);
/*
 * DELETE [Person] WHERE [Person].[Id] = 1
 */

/* 批量删除满足条件的数据 */
dbContext.Delete<Person>(a => a.Age > 18);
/*
 * DELETE [Person] WHERE [Person].[Age] > 18
 */

/* 复杂条件删除 */
dbContext.Delete<Person>(a => !dbContext.Query<City>().Select(a => a.Id).ToList().Contains(a.CityId));
/*
 * DELETE FROM [Person] WHERE NOT ([Person].[CityId] IN (SELECT [City].[Id] AS [C] FROM [City] AS [City]))
 */