Published on

Entity Framework Bulk Update

image
Authors
  • avatar
    Name
    David Jimenez
    Twitter

Imagine you have an application that stores users' documents. The applications facilitates the usual operations of Creating, Reading, Updating and Deleting (CRUD) files. Over time, you have found that users sometimes accidentally delete a number of their files.

To help out clients, you decide to implement soft delete: you add a flag to indicate that a file has been deleted. Recovering files then becomes a simple matter of toggling that flag.

If using Entity Framework, the C# entity might look something like this:

 public class Document
 {
    public Guid Id { get; set; }
 
    public string FileName { get; set; } = string.Empty;
 
    public string FileExtension { get; set; } = string.Empty;
 
    public string ContentType { get; set; } = string.Empty;
 
    public bool IsDeleted { get; set; }
 }

The SQL table will have columns matching each of the properties in the entity.

If a user is deleting a number of documents, we might be tempted to loop through those documents, and update them one by one. However, if we were using raw SQL, we could run a simple update statement:

UPDATE dbo.Document
SET IsDeleted = 1
WHERE Id in ('GUID_1', 'GUID_2', ...)

EF Core 7.0 introuduced the ability to do just that:

await _dbContext.Documents
    .Where(document => targetDocumentIds.Contains(document.Id))
    .ExecuteUpdateAsync(sp => sp.SetProperty(document => document.IsDeleted, true));

where targetDocumentIds is a collection (e.g., a HashSet) of ids for the documents we want to delete.

For additional information, you can check out Microsoft's documentation.