我希望提高数据集的更新性能并寻求见解。
我在表
TestResults
中有一组 2000 行数据,当新数据集可用时,所有 2000 行数据都必须使用各自的值进行更新,在本例中为 ratingDate
和 rating
。
// The class
public class TestResults
{
//...other properties
public int Rating {get;set}
public DateTime RatingDate {get;set;}
//...other properties
}
// updating with latest data
foreach(var item in updatedTestResults)
{
context.TestResults
.Where(x => x.Id == item.Id)
.ExecuteUpdate(setters => setters
.SetProperty(b => b.RatingDate, item.RatingDate)
.SetProperty(b => b.Rating, item.Rating));
}
await context.SaveChangesAsync();
我的理解是,这将为每个条目(大约 2000 个)生成 SQL 更新请求。
有没有更好、更高效的方式来进行更新?
您可以使用扩展linq2db.EntityFrameworkCore,请注意,我是创建者之一。
using var db = context.CreateLinqToDBConnection();
var simplifiedData = updatedTestResults.Select(x => new { x.Id, x.RatingDate, x.Rating });
// create temporary table
using var tempTable = await db.CreateTempTableAsync(simplifiedData, tableName: "tempTestResults");
// join temporary table with table which should be updated
var updateQuery =
from tr in context.TestResults
join t in tempTable on tr.Id equals t.Id
select new { tr, t };
// execute Update query
await updateQuery
.Set(x => x.tr.RatingDate, x => x.t.RatingDate)
.Set(x => x.tr.Rating, x => x.t.Rating)
.UpdateAsync();