简体   繁体   English

更新多行的快速方法

[英]Quick way to update many rows

I'm developing a system that, when working, will update a given number of rows in DB with an new ID. 我正在开发一个系统,该系统在工作时将使用新ID更新数据库中给定数量的行。

Currently I have ~9 million rows and after selecting a small subset of that data (~10k items) I then want to iterate through each of these items and update one column with a new ID. 目前,我有大约900万行,在选择了该数据的一小部分(大约1万个项目)之后,我想遍历每个项目并用新ID更新一列。

What I have currently does work but is too slow to be usable so I need to improve it somehow. 我目前所能做的,但是太慢了,无法使用,因此我需要以某种方式进行改进。 Here's the code, this was originally a ForEach loop but I read that 'For' loops on Arrays were quicker so I tried that without much improvement. 这是代码,它原本是一个ForEach循环,但是我读到数组上的“ For”循环更快,所以我尝试了一下却没有太大的改进。

public string UpdateWithNewWidgetId(List<string> allTheWidgetIds, int newWidgetId)
    {
  var repoPerson = _repositoryFactory.CreateRepository<Person>();

        try
        {
            var person = repoPerson.GetAll(x => fieldToUpdate.Any(val => x.WidgetId == val)).ToArray;


            for (int i = 0; i < person.Length; i++)
            {
                person[i].WidgetId= newWidgetId;
                repoPerson.Update(person[i]);
            }

            repoPerson.SaveChanges();
        }
        catch (Exception ex)
        {
            //log error
        }

So, the repoPerson returns a list of about 10K items pretty quickly but the foreach loop takes ages and then the SaveChanges (this just does a Context.SaveChanges()) takes even longer. 因此,repoPerson很快返回了约1万个项目的列表,但是foreach循环需要一定的时间,然后SaveChanges(这只是执行Context.SaveChanges())就需要更长的时间。

Initially I had the SaveChanges within the foreach and thought that was my issue, but removing it from the loop hasn't improved things. 最初,我在foreach中包含SaveChanges,并认为这是我的问题,但是将其从循环中删除并没有改善。

For large data amount you need to look through this topic: 对于大量数据,您需要仔细阅读以下主题:

Bulk Update in C# 用C#批量更新

Generally if you need to perform a large amount of inserting/updating data, Entity Framework is not enough - need to use SqlBulkCopy approach which is much much faster. 通常,如果您需要执行大量的插入/更新数据,则Entity Framework是不够的-需要使用SqlBulkCopy方法,该方法要快得多。

Try to add transaction, should speed up context SaveChanges event 尝试添加事务,应加快上下文SaveChanges事件

using (Context context = new Context())
        {
            using (var dbContextTransaction = context.Database.BeginTransaction())
            {
             ...yours code
             context.SaveChanges();
             dbContextTransaction.Commit();
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM