> For the complete documentation index, see [llms.txt](https://monksoul.gitbook.io/hoa/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://monksoul.gitbook.io/hoa/shujukucaozuoshinan/piliangzenshangaicaozuo.md).

# 9.8、批量增删改操作

批量操作也算比较常见的功能，通常性能是最大考虑因素。

在 Hoa Framework 框架中，默认集成了高性能且易用的第三方包：[EFCore.BulkExtensions](https://github.com/borisdj/EFCore.BulkExtensions)。使用极其简单，且是**微软推荐的EF Core 批量操作库**。

### 常见示例

```csharp
// 批量插入
_testRepository.Context.BulkInsert(entitiesList);                   
_testRepository.Context.BulkInsertAsync(entitiesList);

// 批量更新
_testRepository.Context.BulkUpdate(entitiesList);                   
_testRepository.Context.BulkUpdateAsync(entitiesList);

// 批量删除
_testRepository.Context.BulkDelete(entitiesList);                   
_testRepository.Context.BulkDeleteAsync(entitiesList);

// 批量插入或更新
_testRepository.Context.BulkInsertOrUpdate(entitiesList);           
_testRepository.Context.BulkInsertOrUpdateAsync(entitiesList);

// 批量插入或更新或删除
_testRepository.Context.BulkInsertOrUpdateOrDelete(entitiesList);   
_testRepository.Context.BulkInsertOrUpdateOrDeleteAsync(entitiesList);

// 批量读取多个实体
_testRepository.Context.BulkRead(entitiesList);                     
_testRepository.Context.BulkReadAsync(entitiesList);

// 批量清空表（慎用！！！！！）
_testRepository.Context.Truncate<Entity>();                         
_testRepository.Context.TruncateAsync<Entity>();
```

### 链式查询批量操作

```csharp
// 根据条件批量删除
_testRepository.Entity.Where(a => a.ItemId >  500).BatchDelete();
_testRepository.Context.Items.Where(a => a.ItemId >  500).BatchDeleteAsync();

// 根据条件批量更新
_testRepository.Entity.Where(a => a.ItemId <= 500).BatchUpdate(a => new Item { Quantity = a.Quantity + 100 });
_testRepository.Entity.Where(a => a.ItemId <= 500).BatchUpdate(new Item { Description = "Updated" });
_testRepository.Entity.Where(a => a.ItemId <= 500).BatchUpdateAsync(new Item { Description = "Updated" });

// 批量更新指定列
var updateColumns = new List<string> { nameof(Item.Quantity) };
var q = _testRepository.Entity.Where(a => a.ItemId <= 500);
int affected = q.BatchUpdate(new Item { Description = "Updated" }, updateColumns);
```

更多批量操作[可查看官方文档](https://github.com/borisdj/EFCore.BulkExtensions)。
