我正在使用EF 6。我试图在每插入100个实体后将更改保存到数据库,共插入约200,000个实体。
问题是,保存50,000个实体花费了11个小时,而且仍然很慢。我正在使用WebJobs运行此操作,并且作业发布在与主网站相同的Azure Web应用程序上。这是因为WebJob没有足够的资源,还是因为每插入100个实体后保存的方式不正确,或者是方法本身的问题?
问题是,保存50,000个实体花费了11个小时,而且仍然很慢。我正在使用WebJobs运行此操作,并且作业发布在与主网站相同的Azure Web应用程序上。这是因为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();
}
}
}
EntityFramework.BulkInsert
这样的组件或其他类似的组件(在你喜欢的搜索引擎上搜索“Entity Framework bulk insert” - 你会找到几个,选择你最喜欢的一个)。 - marc_s