刷新对象实体框架范围内使用更新的值 [英] Reload object in an Entity Framework context with updated values
问题描述
我有我从数据库中拉出的EF对象。然后,我通过做一个函数调用的更新到数据库中的相应行,它使用另一个的DbContext
。本更新程序之后,我想重新加载对象的内容与更新的内容,但是EF方面似乎缓存中的内容。
下面是的code样品(我已经删除了一些无关的绒毛,使其更简单):
I have an EF object that I pull from the db. I then make an update to the corresponding row in the DB through a function call which uses another DBContext
. After this update, I would like to reload the contents of the object with the updated contents, however the EF context seems to cache the contents.
Here's a sample of the code(I've removed some unrelated fluff to make it simpler):
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.
}
我发现我可以用一个新的上下文拉更新的情况下,但这是无效的。
I find that I can use a new context to pull the updated context, but this is inefficient.
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
}
有没有办法重新加载的内容,直接后,我进行了更新?
Is there a way to reload the contents directly after I perform the update?
推荐答案
您应该能够调用 context.Refresh(RefreshMode.StoreWins,伞)
,以确保您拥有最新版本。
you should be able to call context.Refresh(RefreshMode.StoreWins,umbrella)
to make sure you have the latest version.
这篇关于刷新对象实体框架范围内使用更新的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!