如何在ASP.NET MVC中配置AutoMapper属性 [英] How to Configure AutoMapper Attributes in ASP.NET MVC
问题描述
根据 GitHUb 文档,要使用 AutoMapper.Attributes 需要完成以下三个步骤:
According to the GitHUb documentation, To use AutoMapper.Attributes need three steps to be done as follows:
-
创建要映射的类.
Create the classes you'd like to map.
将[MapsTo]属性添加到源类中,并使用目标类型作为参数. (或者,您可以使用[MapsFrom]属性将目标类与源类型进行映射.)
Add the [MapsTo] attribute to the source class, with the destination type as the argument. (Alternatively, you can use the [MapsFrom] attribute to map the destination class with the source type.)
我已经完成了第1步和第2步,但无法理解如何以及在何处使用第3步:
这是我的Model类:
Here is my Model classes:
[MapsFrom(typeof(ApplicationRole))]
public class RoleViewModel
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Role Name")]
public string Name { get; set; }
public string Description { get; set; }
}
[MapsTo(typeof(RoleViewModel))]
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
public string Description { get; set; }
}
这是我的控制器方法:
public ActionResult Index()
{
List<ApplicationRole> applicationRoles = RoleManager.Roles.ToList();
List<RoleViewModel> roleList = Mapper.Map<List<RoleViewModel>>(applicationRoles);
return View(roleList);
}
有人会告诉我如何和在哪里调用程序集上的 MapTypes() 扩展方法,该方法要按照步骤3的建议从中映射类型 AutoMapper.Attributes 文档.
Would anybody tell me how to and where to Call the MapTypes() extension method on the assembly from which I want to map my types as suggested in step three of the AutoMapper.Attributes documentation.
推荐答案
我将在Controller中(最终在构造函数中)进行操作:
I would do in the Controller (eventually in the constructor):
typeof(RoleViewModel).Assembly.MapTypes();
如果安装Automapper的版本4,则可以解决此问题,因为在最后一个版本中,属性不起作用.因此,请在Package-Manager控制台中添加以下说明:
The problem can be solved if you install version 4 of Automapper because in the last version Attributes are not working. So please add the following instructions in Package-Manager Console:
uninstall-package Automapper
install-package Automapper -version 4.2.1
这篇关于如何在ASP.NET MVC中配置AutoMapper属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!