我有一个从数据库中提取的EF对象。然后,我通过使用另一个DBContext
的函数调用更新DB中的相应行。在此更新之后,我想用更新的内容重新加载对象的内容,但是EF上下文似乎缓存了内容。
这是代码的一个示例(我已经删除了一些不相关的绒毛以使其更简单):
using (UmbrellaEntities context = new UmbrellaEntities())
{
var umbrella = (from u in context.Umbrellas
where u.umbrellaId == umbrellaId
&& !u.deleted
select u).Single();
int oldVersion = umbrella.Version;
updateUmbrellaVersions(); //perform update on table Umbrella using a new `UmbrellaEntities` object.
//ideally I'd like to be able to get the updated umbrella.Version without a new call.
var umbrella = (from u in context.Umbrellas
where u.umbrellaId == umbrellaId
&& !u.deleted
select u).Single();
int newVersion = umbrella.Version; //at this point i expect newVersion to be different from oldVersion, since the value in the db has been updated, but that's not the case.
}
我发现我可以使用新的上下文来提取更新的上下文,但效率很低。
using (UmbrellaEntities context = new UmbrellaEntities())
{
var umbrella = (from u in context.Umbrellas
where u.umbrellaId == umbrellaId
&& !u.deleted
select u).Single();
int oldVersion = umbrella.Version;
updateUmbrellaVersions(); //perform update on table Umbrella using a new `UmbrellaEntities` object.
}
using (UmbrellaEntities context = new UmbrellaEntities())
{
var umbrella = (from u in context.Umbrellas
where u.umbrellaId == umbrellaId
&& !u.deleted
select u).Single();
int newVersion = umbrella.Version; //we have the right value
}
有没有办法在执行更新后直接重新加载内容?
答案 0 :(得分:4)
您应该可以致电context.Refresh(RefreshMode.StoreWins,umbrella)
以确保您拥有最新版本。