Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
767 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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.
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();