Preventing Unchanged Value Updates in ASP.NET MVC and Entity Framework

I am using ASP.NET MVC and Entity Framework. I have a Edit Face web page where I can edit user fields, and 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(); 

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

+5
c # asp.net-mvc entity-framework
Sep 28 '10 at 3:58
source share
2 answers

Well, if you assign a property, then the Entity Framework will assume that you know what you are doing and update it. You say that the user changed only one field, but I'm not sure how MVC or Entity Framework should know that out of all key pairs in the form of POSTed HTML, only one was actually changed by the user, you say in your question that β€œthe values ​​were not changed, "but in your comments on @jchapa's answer you say that" not all data is the same. " This suggests that the actual problem is not what the Entity Framework does, but what you tell it.

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

If your real problem is that the model submitted to the action contains fields that the user can never change and which should never be updated (perhaps because they are not in the form at all), you can pass the TryUpdateModel white list.

If your real problem is that another user could change the Person instance between the time the user issued a GET request for the form and the time when the user completed its changes, you can add the TIMESTAMP field to the table and set the concurrency mode to fixed.

+3
Sep 28 '10 at 13:04 on
source share

You may simply not call the SaveChanges() call if the information is the same.

0
Sep 28 '10 at 4:07
source share



All Articles