Entity Framework Core Interview Question #110

How can EF Core perform a targeted update without loading the complete entity?

Change Tracking, Updates, Transactions & Concurrency Mid-Level Intermediate

Quick Interview Answer

A stub entity containing the key can be attached, and selected properties can be marked as modified. This can avoid a preliminary SELECT when the application already has enough trustworthy information.

Detailed Explanation

A stub entity containing the key can be attached, and selected properties can be marked as modified. This can avoid a preliminary SELECT when the application already has enough trustworthy information.

However, the approach requires care with validation, concurrency, authorization, and original values. It should not be used simply to avoid every read.

For set-based updates affecting multiple rows, ExecuteUpdate may be more appropriate.

Code Example

var product = new Product
{
    Id = id,
    Price = newPrice
};

db.Attach(product);
db.Entry(product)
  .Property(p => p.Price)
  .IsModified = true;

await db.SaveChangesAsync();