gpt4 book ai didi

.net - 使用更新的值在 Entity Framework 上下文中重新加载对象

转载 作者:行者123 更新时间:2023-12-04 23:07:34 24 4
gpt4 key购买 nike

我有一个从数据库中提取的 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
}

有没有办法在我执行更新后直接重新加载内容?

最佳答案

您应该能够调用 context.Refresh(RefreshMode.StoreWins,umbrella) 以确保您拥有最新版本。

关于.net - 使用更新的值在 Entity Framework 上下文中重新加载对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7639219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com