在ASP.NET MVC和Entity Framework prevent更新值不变 [英] Prevent updating unchanged value in ASP.NET MVC and Entity Framework

查看:131
本文介绍了在ASP.NET MVC和Entity Framework prevent更新值不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC和Entity Framework。我有一个编辑个人网页,个人的领域可以进行编辑,然后在回发的动作,我用下面的code。

I am using ASP.NET MVC and Entity Framework. I have an Edit Person web page where person's fields can be edited, then in the post back action, I use the following code.

var person = objectCtx.Persons.Where(s => s.Id == id).FirstOrDefault();
TryUpdateModel(person, form.ToValueProvider());
objectCtx.SaveChanges();

它的伟大工程。然而,在生成的SQL,我仍然可以看到即使数值没有改变UPDATE语句。有没有办法避免这种情况的ASP.NET MVC或实体框架?

It works great. However in the generated SQL, I can still see an UPDATE statement even if the values have not been changed. Is there a way to avoid this in ASP.NET MVC or in Entity Framework?

推荐答案

好吧,如果你指定一个属性,则实体框架将presume你知道自己在做什么,并对其进行更新。你是说,用户更改只有一个字段,但我不知道任何MVC或实体框架应该怎么知道的是,在张贴的HTML表单的所有键值对,只有一个实际上是由用户改变。你是说,在你的问题,即价值没有改变,但在@ jchapa的回答您的意见你说不是所有的信息都是一样的。这表明,实际的问题是不是与什么样的实体框架是干什么的,而是你告诉它做的事。

Well, if you assign a property, then the Entity Framework will presume you know what you're doing and update it. You're saying that the user changed only one field, but I'm not sure how either MVC or the Entity Framework is supposed to know that, of all the keyvalue pairs in the POSTed HTML form, only one was actually changed by the user. You are saying, in your question, that "the values have not been changed," but in your comments on @jchapa's answer you say that "not all information is the same." This suggests that the actual issue is not with what the Entity Framework is doing, but rather what you are telling it to do.

我想,也许您正在寻找在错误的地方解决。

I think that perhaps you are looking for a solution in the wrong place.

如果你真正的问题是,传递到操作的模型中包含了用户永远不能改变,这决不应该被更新(这或许是因为他们没有真正的形式在所有的)领域,那么你可以通过一个白名单 TryUpdateModel

If your real problem is that the model passed to the action contains fields which the user can never change and which should never be updated (perhaps because they are not actually on the form at all), then you can pass a whitelist to TryUpdateModel.

如果你真正的问题是,其他用户可能已经改变了用户发出的形式和用户发布了她的变化时的GET请求的时间之间的实例,那么你可以时间戳字段添加到表并在其上设置固定的并发模式。

If your real problem is that another user might have changed the Person instance between the time the user issued a GET request for the form and the time the user POSTed her changes, then you can add a TIMESTAMP field to the table and set fixed concurrency mode on it.

这篇关于在ASP.NET MVC和Entity Framework prevent更新值不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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