C# 在 ASP.Net MVC 中使用 AutoMapper 的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16477498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to use AutoMapper in ASP.Net MVC
提问by Mark
I'm trying to start using ViewModels - but I'm having trouble with this POST not validating - the values in the model are shown in the Watch part below the code:
我正在尝试开始使用 ViewModels - 但我在此 POST 未验证时遇到问题 - 模型中的值显示在代码下方的 Watch 部分中:
ModelStats.IsValid = false
ModelStats.IsValid = false


My ItemViewModel is:
我的 ItemViewModel 是:
public class ItemViewModel
{
public int ItemId { get; set; }
[Display(Name = "Item")]
public string ItemName { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
[Display(Name = "Price")]
public double UnitPrice { get; set; }
[Range(0.00, 100, ErrorMessage = "VAT must be a % between 0 and 100")]
public decimal VAT { get; set; }
[Required]
public string UserName { get; set; }
}
I'm sure it will be something simple - but I've just been looking at it so long, I can't figure out what I'm doing wrong. Can anyone please advise?
我相信这会很简单 - 但我已经看了这么久,我无法弄清楚我做错了什么。任何人都可以请指教吗?
Thanks, Mark
谢谢,马克
采纳答案by Satpal
As far as Validation failure is concerned.
就验证失败而言。
If you don't intend to supply UserNamein the form, then remove the [Required]attribute from ItemViewModel
如果您不打算UserName在表单中提供,[Required]则从ItemViewModel
In order to Use AutoMapper. You need to create a map, such as
为了使用AutoMapper。您需要创建一个地图,例如
Mapper.CreateMap<Item, ItemViewModel>();
And then map
然后映射
var itemModel = Mapper.Map<Item, ItemViewModel>(model);
Note: CreateMaphas to be created only once, you should register it at Startup. Do read How do I use AutoMapper?.
注意:CreateMap必须只创建一次,您应该在启动时注册它。请阅读如何使用 AutoMapper?.
回答by Adi
Make sure your ItemViewModel, Itemclasses have same fields or not. If same fields with same Datatypes AutoMapper works fine.
确保您的ItemViewModel,Item类具有相同的字段。如果具有相同数据类型的相同字段 AutoMapper 工作正常。
Mapper.CreateMap< Item, ItemViewModel>();
Mapper.Map< Item, ItemViewModel>(ItemVM);
If Fields are not same in both the classes make sure that same with Custom Mapping.
如果两个类中的字段不相同,请确保与自定义映射相同。
Mapper.CreateMap<UserDM, UserVM>().ForMember(emp => emp.Fullname,
map => map.MapFrom(p => p.FirstName + " " + p.LastName));
In the above Custom Mapping Fullnameis UserVMfield that maps with FirstName, LastNamefields from UserDM(here UserDMis Domain Model, UserVMis View Model).
在上面的自定义映射中,Fullname是UserVM与FirstName,LastName字段映射的字段UserDM(这里UserDM是域模型,UserVM是视图模型)。

