【发布时间】:2020-12-07 05:55:57
【问题描述】:
我想对一百万多行执行批量更新。
但是,我不想更新整个表,而是分批更新(以防止锁定整个表)。每 10,000 行说一次。
例如,类似于这个答案:How to update large table with millions of rows in SQL Server?
目前使用 UpdateFromQuery 不加载整个上下文,直接更新数据库。
现在如何批量更新?我应该使用.Take 函数吗?
var productUpdate = _dbContext.Set<Product>()
.Where(x => x.ProductType == 'Electronics')
.UpdateFromQuery( x => new Product { ProductBrand = "ABC Company" });
目标代码:
How to update large table with millions of rows in SQL Server?
SET @BatchSize = 10000;
SET @Rows = @BatchSize; -- initialize just to enter the loop
BEGIN TRY
WHILE (@Rows = @BatchSize)
BEGIN
UPDATE TOP (@BatchSize) prod
SET Value = 'ABC Company'
FROM dbo.Products prod
WHERE prod.ProductType = 'Electronics'
SET @Rows = @@ROWCOUNT;
END;
注意:目前除非需要,否则不要使用 RawSql
【问题讨论】:
-
嗨 @SalahAkbari 是的,我们知道 rawsql 和 fromsql,只想查看使用 EF 扩展和更新的注释,谢谢
标签: c# .net entity-framework asp.net-core entity-framework-plus