文章目录
- 一、前言
- 二、批量操作数据库记录方案
-
- 1、添加开源插件:
- 2、批量更新记录Index:
- 三、总结
一、前言
EntityFrameWork 中没有批量操作数据库的方法,如:批量更新、批量删除等…
可以通过DbContext来执行Sql语句,不是特别优雅和推荐;
优雅的方式当然是使用开源的现成轮子…
二、批量操作数据库记录方案
1、添加开源插件:
nuget 搜索添加 Z.EntityFramework.Plus
2、批量更新记录Index:
/// <summary>
/// 找到指定Id记录,后面记录Index自动批量+1
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task IndexIncreaseAfterIdAsync(int id)
{
var tmpEntity = this.DbContext.PresetCruise_Points.FirstOrDefault(p => p.Id == id);
if (tmpEntity == null)
{
return;
}
//扩展方法 条件:比tmpEntity.Index 大的记录
await this.DbContext.PresetCruise_Points.Where(p => p.Index > tmpEntity.Index)
//批量执行:Index=Index+1;
.UpdateAsync(p => new PresetCruise_Points() { Index = p.Index + 1 });
}
三、总结
难者不会,会了就不难了;
Z.EntityFramework.Plus基础功能免费,高级功能收费;
还有一个开源插件EFCore.BulkExtensions 不过目前暂时不支持MySql,只支持 Sqlite 和 MsSql;