3

为什么 DbContextctx在每次SaveChanges()执行后处理得更快?

第一个样本:

var ctx = new DomainContext(); 
foreach (var item in deals)
        {
            DealsOfReutersAddition newDealAddition =
                        new DealsOfReutersAddition
                        {
                            DealsOfReutersId = item.DealsOfReutersId,
                            DealDate = DateTime.Parse(item.DateConfirmed ?? "01 01 01", new CultureInfo("en-US")),
                        };
            ctx.DealsOfReutersAdditions.Add(newDealAddition);
            ctx.SaveChanges();
        }

ctx.Dispose();

第二个样本:

foreach (var item in deals)
        {
            DealsOfReutersAddition newDealAddition =
                        new DealsOfReutersAddition
                        {
                            DealsOfReutersId = item.DealsOfReutersId,
                            DealDate = DateTime.Parse(item.DateConfirmed ?? "01 01 01", new CultureInfo("en-US")),
                        };
            var ctx = new DomainContext(); 
            ctx.DealsOfReutersAdditions.Add(newDealAddition);
            ctx.SaveChanges();
            ctx.Dispose();
        }

在 1000 行上,第二个样本估计为 8 秒,而第一个样本为 140 秒。有什么方法可以清理 ctx 而不是重新创建?

4

1 回答 1

4

正如@JensKloster 在评论中所说的那样,您绝对不想SaveChanges在循环中每次都调用。但我实际上会抵制将其置于循环之外的诱惑。随着上下文跟踪的对象数量越来越多,会用完更多的内存,这会使保存变得越来越慢。

那么,我为您提供的解决方案是在循环中设置一个正在运行的计数器来确定您何时进行保存:

int numberOfRecords = 0;
using(var ctx = new DomainContext())
{
  foreach (var item in deals)
          {
              DealsOfReutersAddition newDealAddition =
                          new DealsOfReutersAddition
                          {
                              DealsOfReutersId = item.DealsOfReutersId,
                              DealDate = DateTime.Parse(item.DateConfirmed ?? "01 01 01", new CultureInfo("en-US")),
                          };

              ctx.DealsOfReutersAdditions.Add(newDealAddition);

              numberOfRecords++;
              if(numberOfRecords % 500 == 0) //Saves after every 500 rows.
              {
                ctx.SaveChanges();
              }
           }
}
于 2013-03-14T13:40:27.583 回答