0

I have added two fields(A, B) to my table. I have these fields populated when I do new registration. However, when I do an update to a form without those fields included, it seems to erase the values in fields (A, B). Is there a way to set validations in the controller or model to prevent them from being updated, when I am not passing values to update it?

tereško
  • 58,060
  • 25
  • 98
  • 150
user1929393
  • 4,089
  • 7
  • 30
  • 48
  • This is yet another classic example of misunderstanding what a ViewModel does. There are two articles here in SO, [this one](http://stackoverflow.com/questions/9326450/in-mvc-what-is-a-viewmodel) and [another one](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) that has an example that will give you an idea what it does. Basically, if you have an entity that you do not want to have all fields updated, then that's a candidate for having a viewmodel. But I would suggest to use viewmodel every time. – von v. Apr 09 '13 at 00:10

1 Answers1

2

Entity framework updates all fields that have changed. EF sees a null value as a change if your field has data.

You should instead be retrieving the record, updating only the fields you want to change, then re-saving.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • Does this mean I need to include the field in the form when updating? Is there a way to not include the field in the form and still have the EF not update it? – user1929393 Apr 08 '13 at 23:24
  • @user1929393, easiest way to do that is to pull the object from the database, update the appropriate fields, then save – Chris Curtis Apr 08 '13 at 23:59
  • @user1929393 - no, it means on post you retrieve the record from the database, then update the fields you want to change, then save changes. – Erik Funkenbusch Apr 09 '13 at 13:39