简体   繁体   English

在ASP.NET MVC中跟踪从ViewModel到Model的实体跟踪字段

[英]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. 无法在控制器的[HttpPost]更新操作方法中使用AutoMapper。

I have Entity tracking fields such as CreatedDate, CreatedBy, ModifiedDate, ModifiedBy and I do not have them as fields in my ViewModel. 我有诸如CreatedDate,CreatedBy,ModifiedDate,ModifiedBy之类的实体跟踪字段,并且在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. 将跟踪字段添加到视图模型中,并在HTML中将其作为隐藏字段添加,就像“ Id”一样,以便将它们发布回服务器。

  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. 无需创建新的产品对象,而是基于viewModel.Id从数据库中检索产品,然后使用viewModels新值手动覆盖用户可能已经以表格形式编辑的所有值。

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. 第1步是将多余的数据发送到我不需要的页面,第2步是没有AutoMapper的额外的数据库调用和不干净的代码。

I would use option 2. 我会使用选项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. 首先,它停止了html注入攻击,用户可以简单地编辑您的html并更改您不打算公开进行编辑的字段。

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. 在添加额外的属性时,您无需担心,这些属性需要将它们继承到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. 用户通常不介意在保存操作上再多花一点时间,这使他们对应用程序实际正在执行的操作感到满意。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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