【发布时间】:2017-09-28 18:32:10
【问题描述】:
我正在使用 Microsoft SQL Server 和实体框架。我有 N 个(例如 10 000 个)要插入的项目。在插入每个项目之前,我需要插入或更新现有组。由于性能低下,它不能很好地工作。这是因为我生成了太多查询。每次在循环中,我都通过三个(已编入索引的)参数查询Groups 表来查找组。
我正在考虑首先使用 WHERE IN 查询 (Groups.Where(g => owners.Contains(g.OwnerId) && .. ) 查询所有组,但我记得此类查询受参数数量的限制。
也许我应该写一个存储过程?
这是我的示例代码。我正在使用 IUnitOfWork 模式来包装 EF DbContext:
public async Task InsertAsync(IItem item)
{
var existingGroup = await this.unitOfWork.Groups.GetByAsync(item.OwnerId, item.Type, item.TypeId);
if (existingGroup == null)
{
existingGroup = this.unitOfWork.Groups.CreateNew();
existingGroup.State = GroupState.New;
existingGroup.Type = item.Code;
existingGroup.TypeId = item.TypeId;
existingGroup.OwnerId = item.OwnerId;
existingGroup.UpdatedAt = item.CreatedAt;
this.unitOfWork.Groups.Insert(existingGroup);
}
else
{
existingGroup.UpdatedAt = item.CreatedAt;
existingGroup.State = GroupState.New;
this.unitOfWork.Groups.Update(existingGroup);
}
this.unitOfWork.Items.Insert(item);
}
foreach(var item in items)
{
InsertAsync(item);
}
await this.unitOfWork.SaveChangesAsync();
【问题讨论】:
标签: c# sql-server entity-framework insert bulkinsert