简体   繁体   中英

Keeping track of Entity Tracking fields from ViewModel to Model on Update in ASP.NET MVC

Unable to use AutoMapper in the [HttpPost] Update action method in my controller.

I have Entity tracking fields such as CreatedDate, CreatedBy, ModifiedDate, ModifiedBy and I do not have them as fields in my ViewModel.

When the user posts the form in the Update action method I would typically do something like:

var product = Mapper.Map<Product>(productViewModel);

At this point the tracking fields are null. I can never get them.

It looks like I have two options:

  1. Add the tracking fields to the view model and in the html as hidden fields just like 'Id' so they are posted back to the server.

  2. Instead of creating a new product object, retrieve the product from the database based on viewModel.Id and then manually overwrite all of the values that could have been edited by the user in the form with the viewModels new values.

Does anyone have any additional thoughts or recommendations on this? Step 1 is extra data going to the page that I don't need and Step 2 is an extra database call and unclean code without AutoMapper.

I would use option 2.

Firstly it stops html injections attacks, users could simply edit your html and change fields that you do not intend to expose for edit.

Secondly it's hard to go wrong when editing or adding fields to your base model. You won't have to worry when adding extra properties that you need to carry them over on your viewModel.

Thirdly, unless it's a giant object the database call isn't going to add much delay. Users normally don't mind waiting a little bit more on save operations anyway, makes them feel comfy that the app is actually doing something. :)

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