I have a simple application that is connected to a database (Entity Framework, code first). I have a screen that is used to update an entry to the database. I am able to update the database with the following code:
public void UpdatePlayer()
{
Player playerInDb = GetPlayerFromDb(_player.Id);
playerInDb.Name = Name;
playerInDb.Score = Score;
_context.SaveChanges();
TryClose();
}
private Player GetPlayerFromDb(int id)
{
return _context.Players.Single(p => p.Id == id);
}
If I refresh the database immediately after calling SaveChanges, I can see the changes in the actual database, but if I look at _context.Players, the old values are still there. It is only after I close my app and reopen it that the changes appear in the DbContext. How can I make sure the updated data from the database appears on my DbContext after calling SaveChanges?
UPDATE:
I've changed my code to the following:
public void UpdatePlayer()
{
Player playerInDb = GetPlayerFromDb(_player.Id);
playerInDb.Name = Name;
playerInDb.Score = Score;
using (var context = new ApplicationDbContext())
{
context.Players.Attach(playerInDb);
context.Entry(playerInDb).State = EntityState.Modified;
context.SaveChanges();
}
TryClose();
}
I still have the same issue. The record is updated in the db but not in the application, so my UI does not get updated with the new data. Even if I reload the entire collection of players from the db, nothing gets updated until I completely relaunch the application.