Entity Framework Modified State (updating row values)
Pogłębiając moją wiedzę nt. Entity Framework zauważyłem pewną ciekawą właściwość, mianowicie w syt. gdy tylko niektóre kolumny w wierszu z danymi zostały zaktualizowane, to Entity Framework zachowuje się w różny sposób dla różnego rodzaju aplikacji:
-
dla aplikacji okienkowych (windows forms) aktualizuje tylko wybrane kolumny danego rekordu
-
dla aplikacji webowych (asp) aktualizuje wszystkie kolumny danego rekordu
In a desktop application, state changes are typically set automatically. In this type of application, you read an entity and make changes to some of its property values. This causes its entity state to automatically be changed to
Modified. Then when you callSaveChanges, the Entity Framework generates a SQLUPDATEstatement that updates only the actual properties that you changed.However, in a web application this sequence is interrupted, because the database context instance that reads an entity is disposed after a page is rendered. When the
HttpPostEditaction method is called, this is the result of a new request and you have a new instance of the context, so you have to manually set the entity state toModified.Then when you callSaveChanges, the Entity Framework updates all columns of the database row, because the context has no way to know which properties you changed.If you want the SQL
Updatestatement to update only the fields that the user actually changed, you can save the original values in some way (such as hidden fields) so that they are available when theHttpPostEditmethod is called. Then you can create aStudententity using the original values, call theAttachmethod with that original version of the entity, update the entity’s values to the new values, and then callSaveChanges.For more information, see Add/Attach and Entity States and Local Data on the Entity Framework team blog.