当第一次更改时,EF 4.0 在两次查询后获得相同的值

发布于 2024-12-10 11:41:42 字数 486 浏览 0 评论 0原文

我有一种情况,我需要在从数据库获取后更改其中一个对象的属性值,但在更改之后(不向数据库提交更改),我需要再次查询数据库并获取更改之前的先前状态。

我当前遇到的行为是,我在两种状态下都获得相同的值(更改和未更改)。

var app = mApplicationRepository.GetByID(id);
 app.ApplicationStatus = (int)AppStatus.Applied;
 engine.Parameter = app;
 var appPreviousState = applicationRepository.GetByID(app.ID);
 engine.PreviousState = appPreviousState;
 if (appPreviousState.ApplicationStatus != app.ApplicationStatus)//Allways false
 {
     //call to some method
 }

I have a case in which, I need to change the property value in one of the objects after getting from DB, but after the change (without commiting changes to DB), I need to query again DB and get the previous state before change.

Current behaviour I am experiencing is that I am getting the same value in both states (changed and not changed).

var app = mApplicationRepository.GetByID(id);
 app.ApplicationStatus = (int)AppStatus.Applied;
 engine.Parameter = app;
 var appPreviousState = applicationRepository.GetByID(app.ID);
 engine.PreviousState = appPreviousState;
 if (appPreviousState.ApplicationStatus != app.ApplicationStatus)//Allways false
 {
     //call to some method
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜雨飘雪 2024-12-17 11:41:43

您遇到的问题是原始对象(应用程序)附加到当前上下文。当您更改它时,它会将实体状态更改为已修改,但您然后从相同的上下文中再次获取它,导致它被重新加载。有几种方法可以处理这个问题,但最简单的方法是在从数据库获取对象后将其与上下文分离。当您想要保存更改时,您必须再次附加它。

分离对象: http://msdn.microsoft.com/en-us/library/ bb738697.aspx

应用分离对象的更改:http://msdn.microsoft.com/en-us/library/bb896248.aspx

另一种选择是为原始对象和更新对象提供单独的上下文。

The issue you are running into is the fact that the original object (app) is attached to the current context. When you change it, it changes the entitystate to modified but you then grab it again from the same context causing it to be reloaded. There are a couple ways to deal with this but the easiest would be to detach the object from the context after you get it from the DB. You will have to attach it again when you want to save the changes.

Detach object: http://msdn.microsoft.com/en-us/library/bb738697.aspx

Apply changes from detached object: http://msdn.microsoft.com/en-us/library/bb896248.aspx

Another option would be to have seperate contexts for the original and updated objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文