当第一次更改时,EF 4.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您遇到的问题是原始对象(应用程序)附加到当前上下文。当您更改它时,它会将实体状态更改为已修改,但您然后从相同的上下文中再次获取它,导致它被重新加载。有几种方法可以处理这个问题,但最简单的方法是在从数据库获取对象后将其与上下文分离。当您想要保存更改时,您必须再次附加它。
分离对象: 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.