diff --git a/EntityFrameworkCore.Console/Program.cs b/EntityFrameworkCore.Console/Program.cs index 35d691b..2cd74aa 100644 --- a/EntityFrameworkCore.Console/Program.cs +++ b/EntityFrameworkCore.Console/Program.cs @@ -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 }; diff --git a/README.md b/README.md index 4410776..00ba677 100644 --- a/README.md +++ b/README.md @@ -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. \ No newline at end of file