Im writing an web application with MVC using Entity Framework for my backend logic. My problem is that I have an entity that has certain fields that should never be changed on an update. I am not really sure what the best way to solve this problem would be. There is going to be a lot of data processed in my application, so I cant afford to just hack up a solution.
Is it possible to just define the fields as readonly in the POCO entities ? Or should I write and entity framework extension class that validates all updates. Could it be done in the mapping files between EF and the actual database?
I am relatively new with EF, so I hope some of you might be able to give me some pointers!
Thanks!
Well I would advice against ever using the EF classes in the View. You’re best bet is to construct ViewModel classes and use Automapper to map them from the EF classes.
When you are updating records in the database though, you can control which fields in the ViewModel are used to update the existing fields in the EF class.
The normal process would be:
Use the Id to get the latest version of the existing object out of the database.
If you are using optimistic concurrency control then check that the object has not been updated since the ViewModel was created (so check timestamp for example).
Update this object with the required fields from your ViewModel object.
Persist the updated object back to the database.
Update to include Automapper examples:
Let’s say your POCO is
and Field1 is the field you don’t want updating.
You should declare a view model with the same properties:
and Automap between them in the constructor of your Controller.
you can if you wish (although I prefer to do this manually, automap the other way too:
When you are sending date to your website you would use:
to create the viewModel.
When saving the data, you’d probably want something like:
although I’d probably remove the exclusion of Field1 above and do something like:
note I believe that best-practise would have you never Automap FROM the ViewModel, but to always do this manually, including for new items.