简体   繁体   English

C# 实体框架:仅更新第一批记录并停止

[英]C# Entity Framework: Update Only First Batch Records and Stop

Is there way with EF Core Bulk extensions to only update first few 10000 rows? EF Core Bulk 扩展有没有办法只更新前几 10000 行? write message, update next batch, write message in loop until complete?写消息,更新下一批,循环写消息直到完成?

I know there is Batch Size, however if there is only 5 million to update, and I want only update a certain amount, write a message, in continual loop until complete, how can this be done?我知道有批量大小,但是如果只有 500 万要更新,我只想更新一定数量,写一条消息,不断循环直到完成,这怎么办?

Should I use Top or Take?我应该使用 Top 还是 Take?

I want to write "Hello", every few batches.我想每隔几批写一个“你好”。

while {

await _dbContext.Set<Product>()
    .Where(x => x.Manufacturer == "ABC Company" &&
                x.StartYear == 2019 &&
                x.ProductType.ProductTypeDescription == "Electronics")
    .BatchUpdateAsync(x => new Product(){
                Manufacturer = "XYZ Company",
                StartYear = 2020 });

Console.WriteLine("hello"):

https://github.com/borisdj/EFCore.BulkExtensions https://github.com/borisdj/EFCore.BulkExtensions

Using EF Core 3.1.使用 EF Core 3.1。

Company does not want to use SignalR公司不想用 SignalR

It looks like BatchSize is only used for bulk insert.看起来 BatchSize 仅用于批量插入。 For update the expression is translated to a single SQL UPDATE statement, which doesn't operate by "batches".对于更新,表达式被转换为单个 SQL UPDATE 语句,该语句不按“批处理”操作。

Try this.尝试这个。

if loop until first few 10,000 if 循环直到前几个 10,000

int iEnd = 5;

for (var i = 0; i <= iEnd; i++)
{
    var products = await _dbContext.Set<Product>().Where(x => x.Manufacturer == "ABC Company" &&
                    x.StartYear == 2019 &&
                    x.ProductType.ProductTypeDescription == "Electronics").Skip(i * 10000).Take(10000).ToList();

    products.ForEach(x =>
    {
         x.Manufacturer = "XYZ Company";
         x.StartYear = 2020;
    });
    _dbContext.Set<Product>().UpdateRange(products); // or you can use BulkUpdate here.
}

_dbContext.SaveChanges();

If loop until 5 millions.如果循环直到 500 万。

int i = 0;
Boolean IsContinue = true;
while (IsContinue)
{
     var products = await _dbContext.Set<Product>().Where(x => x.Manufacturer == "ABC Company" &&
                x.StartYear == 2019 &&
                x.ProductType.ProductTypeDescription == "Electronics").Skip(i * 10000).Take(10000).ToList();

     if (products.Count() == 0)
          IsContinue = false;
     else
     {
          products.ForEach(x =>
          {
                x.Manufacturer = "XYZ Company";
                x.StartYear = 2020;
          });
          _dbContext.Set<Product>().UpdateRange(products); // or you can use BulkUpdate here.
      }
      i++;
}

_dbContext.SaveChanges();

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

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