Do you avoid using update?

Last updated by Brook Jeynes [SSW] 9 months ago.See history

The Update method on an entity in EF Core marks all of its fields as dirty. This will result in all the fields being written back to the database.

Writing the entire record to the database can cause locking issues in the database server if there are foreign key relationships involving the entity being modified.

var entity = context
    .Products
    .FirstOrDefault(item => item.ProductID == id);
        
if (entity != null)
{
    entity.Name = "New name";    
    context.Products.Update(entity);
            
    context.SaveChanges();
}

Figure: Bad example - The whole record is written back to the database.

var entity = context
    .Products
    .FirstOrDefault(item => item.ProductID == id);
        
if (entity != null)
{
    entity.Name = "New name";    
    context.SaveChanges();
}

Figure: Good example - Only the modified fields are written back to the database.

We open source. Powered by GitHub