wtorek, 30 lipca 2013

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 call SaveChanges, the Entity Framework generates a SQL UPDATE statement 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 HttpPost Edit action 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 to Modified. Then when you call SaveChanges, 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 Update statement 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 the HttpPost Edit method is called. Then you can create a Student entity using the original values, call the Attach method with that original version of the entity, update the entity's values to the new values, and then call SaveChanges. For more information, see Add/Attach and Entity States and Local Data on the Entity Framework team blog.
 źródło

Brak komentarzy:

Prześlij komentarz