【发布时间】:2016-03-27 09:16:51
【问题描述】:
我正在使用 EF 6。我尝试插入大约 200.000 个实体,同时在每 100 个实体之后保存对数据库的更改。
问题是保存 50.000 个实体需要 11 个小时,但仍然落后。我正在使用 WebJobs 运行它,并且作业发布在与主网站相同的 azure webapp 上。是因为这个问题和 WebJob 没有足够的资源,还是在 100 个实体后保存,还是方法?
方法
public void SaveLeadsForBuyer(ISenderModel model)
{
var rowCounter = 0;
foreach (var deliveryRecord in model.Customers.Select(customerModel => new DeliveryRecord()
{
BuyerId = model.Buyer.Id,
AspNetUserId = customerModel.Id,
DeliveryType = model.Buyer.DeliveryType,
CreatedOn = DateTime.UtcNow
}))
{
++rowCounter;
_unit.Repository<DeliveryRecord>().Insert(deliveryRecord);
_unit.SaveChangesPartially(rowCounter, 100);
}
_unit.SaveChanges();
}
助手
public static class UnitOfWorkHelper
{
/// <summary>
/// Helper method triggers SaveChanges() after amount of rows provided through "amount" parameter in method
/// </summary>
/// <param name="unit">UnitOfWork object</param>
/// <param name="count">Current amount of rows</param>
/// <param name="saveCount">Amount when to save changes to database</param>
public static void SaveChangesPartially(this IUnitOfWorkAsync unit, int count, int saveCount)
{
if (count % saveCount == 0)
{
unit.SaveChanges();
}
}
}
【问题讨论】:
-
EF 对批量插入非常不利,
INSERT SELECT的运行速度是 EF 的 1000000 倍。 -
这不是您正在做的“批量插入” - 您需要查看
EntityFramework.BulkInsert或其他组件(搜索 在你最喜欢的“实体框架批量插入”搜索引擎上 - 你会找到几个,选择你最喜欢的一个)
标签: c# entity-framework azure azure-webjobs