EFCore performance optimization solution - optimization update

batch processing

EF Core helps minimize round trips by automatically batching all updates together in one round trip. Consider the following situation:

var blog = context.Blogs.Single(b => b.Url == "http://someblog.microsoft.com");
blog.Url = "http://someotherblog.microsoft.com";
context.Add(new Blog { Url = "http://newblog1.microsoft.com" });
context.Add(new Blog { Url = "http://newblog2.microsoft.com" });
context.SaveChanges();

The above action loads the blog from the database, changes its URL, and then adds two new blogs; to apply this change, two SQL INSERT statements and one UPDATE statement are sent to the database. When adding Blog instances, instead of sending them one by one SaveChanges , these changes are tracked in EF Core, executing them in a single round trip when called.

batch update

Suppose you want to give all employees a raise. A typical implementation of this in EF Core looks like this:

foreach (var employee in context.Employees)
{
  employee.Salary += 1000;
}
​
context.SaveChanges();

While this is perfectly valid code, let's analyze what it does from a performance standpoint:

  • A database round trip is performed to load all relevant employees; note that this brings all row data for an employee to the client (even if only salary data is required).
  • EF Core's change tracking creates snapshots when entities are loaded, and then compares those snapshots to the instance to find out which properties changed.
  • Perform a second round trip to the database to save all changes. Although all changes are done in one round trip due to batching, EF Core still sends an UPDATE statement for each employee, which has to be executed by the database.

Relational databases support batch updates, so the above can be rewritten as the following single SQL statement:

UPDATE [Employees] SET [Salary] = [Salary] + 1000;

EF currently does not provide an API for performing batch updates. Before these items were introduced, raw SQL could be used to perform performance-sensitive operations:

context.Database.ExecuteSqlRaw("UPDATE [Employees] SET [Salary] = [Salary] + 1000");

Guess you like

Origin blog.csdn.net/gcf10080353/article/details/131716361