我有一个简单的应用程序,连接着一个数据库(Entity Framework, code first)。我有一个屏幕用于更新数据库中的一条记录。以下代码可以更新数据库:
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);
}
如果我在调用SaveChanges后立即刷新数据库,我可以在实际数据库中看到更改,但是如果我查看_context.Players,则仍然存在旧值。只有在关闭并重新打开应用程序后,更改才会出现在DbContext中。如何确保在调用SaveChanges后从数据库更新的数据显示在我的DbContext中?
更新:
我已将代码更改为以下内容:
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();
}
我仍然遇到同样的问题。记录已经在数据库中更新,但应用程序没有更新,因此我的UI没有使用新数据进行更新。即使我从数据库重新加载玩家的整个集合,也不会更新任何内容,直到我完全重新启动应用程序。
using
语句或更好的是使用IoC容器。https://dev59.com/64fca4cB1Zd3GeqPdxDK - Steve Greeneusing
语句,以及更改入口状态,但仍然没有运气。 - Connor Szczepaniak