我有一个带有一些文本框和一个“保存”按钮的 Windows 窗体。当表单加载时,文本框将填充来自模型中实体的数据。当用户单击“保存”按钮时,每个文本框中的值都会写回实体,然后调用 SaveChanges 将数据提交到数据库。
我想知道检查表单是否包含更改的最佳方法是什么?如果它不包含更改,那么我不需要调用 SaveChanges,并且可以保存将记录写回数据库的操作。如果它确实包含更改并且用户尚未单击“保存”按钮,我希望用户确认不需要保存更改。
我想也许我可以只更新实体的字段,然后在调用 SaveChanges 之前检查其 State 属性,但这会失败,因为更新任何字段(即使具有相同的值)也会导致实体被标记为已修改。
所以,我的问题是,在调用 SaveChanges 之前检查是否确实对表单进行了更改的最佳方法是什么?
谢谢,
马特
I have a Windows Form with some textboxes and a Save button. When the form loads the textboxes are populated with data from an entity in my model. When the user clicks on the save button the values in each textbox are written back to the entity and then SaveChanges is called to commit the data to the database.
What I'd like to know is what is the best way to check if the form contains changes? If it doesn't contain changes then I needn't call SaveChanges and I can save writing the record back to the database. If it does contain changes and the user hasn't clicked on the Save button I want to get the user's confirmation that the changes don't need to be saved.
I thought maybe I could just update the entity's fields and then check its State property before calling SaveChanges but this fails as updating any field, even with an identical value, causes the entity to be marked as modified.
So, my question is, what is the best way to check that changes have actually been made to the form before calling SaveChanges?
Thanks,
Matt
发布评论
评论(2)
您可以检查实体状态。只需将文本框中的数据保存到实体中,然后查看EntityState是否为EntityState.Unchanged。
详细信息请参见:http://msdn.microsoft.com/en-我们/library/system.data.entitystate.aspx
You can check the entity state. Just save the data from the textboxes to the entity ans see if the EntityState is EntityState.Unchanged.
Details here: http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx
实际上,即使使用与前一个字段相同的值来更新字段,也会被视为已修改的实体,并且在大多数情况下,这是正确的业务规则。
您可以做的是保留用于填充表单字段的原始对象的副本,并使用相等比较器将其与当前对象进行比较。它并不漂亮,但它可以在您不能依赖对象状态管理器的修改意见的特定情况下完成工作。
Actually updating the field even with the same value as the previous one counts as a modified entity and in most cases this is the correct business rule.
What you could do is keep a copy of the original object that was used to fill the form fields and compare it with the current one using an equality comparer. It's not pretty but it gets the job done in particular cases where you cannot count on the object state manager's opinion of modified.