【发布时间】:2011-10-03 18:41:54
【问题描述】:
我有一个从数据库中提取的 EF 对象。然后我通过使用另一个DBContext 的函数调用对数据库中的相应行进行更新。在此更新之后,我想用更新的内容重新加载对象的内容,但是 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
}
有没有办法在我执行更新后直接重新加载内容?
【问题讨论】:
-
为什么要使用不同的 dbcontext?
-
你的意思是为什么我在函数
updateUmbrellaVersions中使用新的上下文而不是在此处移动更新代码或将dbContext 传递给更新函数?更新代码调用我无法更改其 API 的服务。
标签: .net entity-framework entity-framework-4