撤消实体框架实体中的更改 [英] Undo changes in entity framework entities

查看:28
本文介绍了撤消实体框架实体中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个微不足道的问题,但是:由于 ADO.NET 实体框架会自动跟踪更改(在生成的实体中)并因此保留原始值,我如何回滚对实体对象所做的更改?

this might be a trivial question but: Since ADO.NET entity framework automatically tracks changes (in generated entities) and therefore keeps the original values, how can I rollback changes made to the entity objects?

我有一个表单,它允许用户在网格视图中编辑一组客户"实体.

I have a form which allows the user to edit a set of "Customer" entities in a grid view.

现在我有两个按钮Accept"和Revert":如果单击Accept",我调用 Context.SaveChanges() 并将更改的对象写回数据库.如果单击还原",我希望所有对象都获得其原始属性值.代码是什么?

Now I have two buttons "Accept" and "Revert": if "Accept" is clicked, I call Context.SaveChanges() and the changed objects are written back to the database. If "Revert" is clicked, I would like for all objects to get their original property values. What would be the code for that?

谢谢

推荐答案

EF 中没有还原或取消更改操作.每个实体在 ObjectStateManager 中都有 ObjectStateEntry.状态条目包含原始值和实际值,因此您可以使用原始值覆盖当前值,但您必须为每个实体手动执行此操作.它不会恢复导航属性/关系的更改.

There is no revert or cancel changes operation in EF. Each entity has ObjectStateEntry in ObjectStateManager. State entry contains original and actual values so you can use original values to overwrite current values but you must do it manually for each entity. It will not reveret changes in navigation properties / relations.

还原更改"的常用方法是处理上下文并重新加载实体.如果您想避免重新加载,您必须创建实体的克隆并在新的对象上下文中修改这些克隆.如果用户取消更改,您仍将拥有原始实体.

The common way to "revert changes" is disposing context and reload entities. If you want to avoid reloading you must create clones of entities and modify those clones in new object context. If user cancel changes you will still have original entities.

这篇关于撤消实体框架实体中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆