Add update example with no-tracking for coach.
This commit is contained in:
parent
963378f2e9
commit
f58ce8f120
@ -13,6 +13,29 @@ using var context = new DeadBallZoneLeagueDbContext();
|
||||
// Rather than raise: "System.InvalidOperationException: Sequence contains no elements."
|
||||
// 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)
|
||||
{
|
||||
var coach = new Coach { Name = name, CreatedDate = DateTime.UtcNow };
|
||||
|
||||
@ -102,3 +102,5 @@ The following states are tracked in the `EntityState.State` property:
|
||||
* **Unchanged**: no changes to the entity.
|
||||
* **Modified**: changes are made to the entity.
|
||||
* **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.
|
||||
Loading…
x
Reference in New Issue
Block a user