简体   繁体   中英

Round trip transformation of ViewModel property in ASP.NET MVC

I'm working on an ASP.NET MVC application and I'm trying to figure out how to support optimistic concurrency. The approach I'm working through right now is to have the web app retrieve an instance of an entity (just a POCO), and build a ViewModel from it. The ViewModel will include an object UnderlyingEntity property that holds the instance of the entity itself. I can put the UnderlyingEntity property in a hidden field in the view, then when the view is submitted, apply the changes to the UnderlyingEntity , and send it off to be updated. Since I've persisted my original entity instance in the hidden field, when I save I have the original timestamp to be used for the concurrency check.

The hurdles I'm trying to overcome with this are:

  1. How do I do round-trip serialization/deserialization of the UnderlyingEntity property. I could serialize it easily enough in the view but how do I get it back to the original type when the form is posted? I think I need a ModelBinder or ValueProvider but I'm not sure exactly where to start.
  2. I'd also like to encrypt/decrypt (edit: or hashing) the value so it's not sitting in the hidden field in plain text. If it were in plain text, it would basically be editable by a user through developer tools. I think if I solve #1, I can do this along with it.

Nope. This is not how to do deal with concurrency in EF.

The best practice is the following steps:

  • Add a new property of type row version or timestamp on your entity. This column will be used by EF to check the version of the row into your database when updating. If the value differs with the current value stored into the database then it will throw an exception.
  • In your Razor wiew just store the value of your row version into a hidden field. (It will generate a Base 64 string like Stephen Muecke spotted in comment)
  • when user send back the data after editing to your application, you map your view model to your entity.
  • When saving the data EF will throw an exception DbUpdateConcurrencyException , catch that exception. In the catch block, you do what you want.

To learn more about that go to this link => https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM