我有一个连接到数据库的简单应用程序( Entity Framework ,代码优先)。我有一个用于更新数据库条目的屏幕。我可以使用以下代码更新数据库:
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 不会使用新数据进行更新。即使我从数据库中重新加载整个玩家集合,在我完全重新启动应用程序之前也不会更新任何内容。
最佳答案
实体本身有一种机制来缓存实体以增加选择等完成两次或多次时的速度时间。您可以通过设置来更改实体的状态。
entity.State = EntityState.Modified;
请考虑使用工作单元概念,而不是在类内共享相同的 dbContext
。这将使用以下语法处理上下文本身:
using(DbContext dbContext = new DbContext())
{
//Do some stuff, update, delete etc
}
如果你没有正确处理上下文,你最终也会给应用程序带来其他问题。
关于c# - 在 DbContext 中看不到 Entity Framework 数据库更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44466958/