ASP.NET Core学习之八 MYSQL批量插入
目的:运用EntityFrameworkCore批量插入数据
一、项目环境
环境:.NET Core 3.1, abp 5.1.0
如果使用sqlserver,推荐使用EFCore.BulkExtensions
二、实现代码
`
using Abp.EntityFrameworkCore;
public class TestAppService
{
private readonly IDbContextProvider _dbContextProvider;
public EvaluationAppService(IDbContextProvider<TestDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
}
/// <summary>
/// 批量插入
/// </summary>
/// <param name="inputs"></param>
/// <returns></returns>
private async Task BatchInsert(List<CreateInput> inputs)
{
List<TestEntity> entities = new List<TestEntity>();
foreach (var item in inputs)
{
var entity = ObjectMapper.Map<TestEntity>(item);
entities.Add(entity);
}
if (entities.Count > 0)
{
var dbContext = _dbContextProvider.GetDbContext();
await dbContext.TestEntity.AddRangeAsync(entities);
}
}
}
`