Add update example with no-tracking for coach.

This commit is contained in:
Kevin Matsubara 2025-04-05 23:23:52 +02:00
parent 963378f2e9
commit f58ce8f120
2 changed files with 25 additions and 0 deletions

View File

@ -13,6 +13,29 @@ using var context = new DeadBallZoneLeagueDbContext();
// Rather than raise: "System.InvalidOperationException: Sequence contains no elements." // Rather than raise: "System.InvalidOperationException: Sequence contains no elements."
// var firstCoach = await context.Coaches.FirstOrDefaultAsync(); // var firstCoach = await context.Coaches.FirstOrDefaultAsync();
async Task UpdateCoach()
{
var coach = await context.Coaches.FindAsync(1);
coach.CreatedDate = DateTime.UtcNow;
await context.SaveChangesAsync();
}
async Task UpdateCoachNoTracking()
{
var coach = await context.Coaches
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Id == 1);
// .FindAsync(1); // cannot be used when using no-tracking.
coach.CreatedDate = DateTime.UtcNow;
Console.WriteLine(context.ChangeTracker.DebugView.LongView);
context.Update(coach); // Set Entity state to be updated.
// Note that also other fields are considered "updated/modified", such as the CreatedDate.
// You can also use:
// context.Entry(coach).State = EntityState.Modified;
Console.WriteLine(context.ChangeTracker.DebugView.LongView);
await context.SaveChangesAsync();
}
async Task InsertCoach(string name) async Task InsertCoach(string name)
{ {
var coach = new Coach { Name = name, CreatedDate = DateTime.UtcNow }; var coach = new Coach { Name = name, CreatedDate = DateTime.UtcNow };

View File

@ -102,3 +102,5 @@ The following states are tracked in the `EntityState.State` property:
* **Unchanged**: no changes to the entity. * **Unchanged**: no changes to the entity.
* **Modified**: changes are made to the entity. * **Modified**: changes are made to the entity.
* **Deleted**: the entity is in the database, but is marked for deletion. * **Deleted**: the entity is in the database, but is marked for deletion.
The `Find` functions require tracking, instead, use the `First` function, with a lambda for the ID.