Sunday, 26 March 2023

Bulk update and Delete in EF core 7 using C#

 EF Core7 released a new feature for Bulk updating and Delete.

Nuggets - Microsoft.EntityFrameworkCore.Relational

To delete a set of entities in bulk, filter out the entities that you want to delete by using the Where method Then, invoke the ExecuteDelete method on the collection of entities to be deleted.

using (var db = new BloggingContext())

{

var blogs = db.Blogs

.Where(b => b.Rating > 3)

.ExecuteDelete();

}

To update entities we need to use the new SetProperty method. The first argument of SetProperty selects the property that must be updated via a lambda, and the second argument is the new value of that property by using a lambda.

using (var db = new BloggingContext())

{

var delete= db.Blogs

.Where(p => p.Rating <= 1_000)

.ExecuteUpdate(p => p.SetProperty(x => x.Url, x => "Updated"));

}