How to use EF Core with SQLite to update multiple records

Phil Cleveland 20 Reputation points
2024-12-18T15:46:08.55+00:00

The following code works to update the first matching record in a SQLite database, but the goal is to update all records that match TeeDate == myDateFormatted.

I am trying to update multiple fields in a SQLite database with a single statement or a loop.
I can update a single record (the first one found in DB) but am unable to get a solution that will update all records that match the query.

Visual Studio 2022, Blazor webapp, .Net 8.0, EF Core 9

This Code below only clears the first matching record.

var teesheetToClear = DB.Teesheets.Where(e => e.TeeDate == myDateFormatted);

teesheetToClear.Player1 = "";

teesheetToClear.Player2 = "";

teesheetToClear.Player3 = "";

teesheetToClear.Player4 = "";

I also tried this code but this did nothing.
await DB.Teesheets 
	.Where(e => e.TeeDate == myDateFormatted) .ExecuteUpdateAsync(s => s 	
	.SetProperty(e => e.Player1, _ => "") 
	.SetProperty(e => e.Player2, _ => "") 
	.SetProperty(e => e.Player3, _ => "") 
	.SetProperty(e => e.Player4, _ => ""));

Thanks for any help you can provide.


Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
767 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,008 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,636 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 55,676 Reputation points
    2024-12-18T16:31:27.82+00:00

    Not sure why you're using the ExecuteUpdateAsync approach. This is non-standard and really designed more for batch updates I believe as it skips most of the stuff that EF is set up to handle such as change tracking.

    Here's simplified code to do what you want.

    
    //Get data to change, note that this returns IQueryable<T>, not a single value
    var teesheetToClear = DB.Teesheets.Where(e => e.TeeDate == myDateFormatted);
    
    //Make changes to everything that matches
    foreach (var item in teesheetToClear)
    {
       item.Player1 = "";
       item.Player2 = "";
       item.Player3 = "";
       item.Player4 = "";
    };
    
    //Done making changes, commit them as a single batch
    await DB.SaveChangesAsync();
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.