Modifying Data with EF Core: More Efficient Updates and Deletes
Learn about data modification in EF Core and explore ExecuteUpdate and ExecuteDelete techniques.
We'll cover the following
The traditional way to modify data with EF Core
The traditional way of modifying data using EF Core is summarized in the following steps:
Create a database context. Change tracking is enabled by default.
To insert, create a new instance of an entity class and then pass it as an argument to the
Add
method of the appropriate collection, for example,db.Products.Add(product)
.To update, retrieve the entities we want to modify and then change their properties.
To delete, retrieve the entities we want to remove and then pass them as an argument to the
Remove
orRemoveRange
methods of the appropriate collection, for example,db.Products.Remove(product)
.Call the
SaveChanges
method of the database context. This uses the change tracker to generate SQL statements to perform the needed inserts, updates, and deletes, then returns the number of entities affected.
Efficient data modifications with ExecuteUpdate
and ExecuteDelete
EF Core 7 introduces two methods that can make updates and deletes more efficient because they do not require entities to be loaded into memory and have their changes tracked. The methods are named ExecuteDelete
and ExecuteUpdate
(and their Async equivalents). They are called on a LINQ query and affect the entities in the query result. Although the query is not used to retrieve entities, no entities are loaded into the data context.
Deleting data using ExecuteDelete
For example, to delete all rows in a table, call the ExecuteDelete
or ExecuteDeleteAsync
method on any DbSet
property, as shown in the following code:
Get hands-on with 1400+ tech skills courses.