根据GitHUb文档,要使用AutoMapper.Attribute,需要完成以下三个步骤:
创建您要映射的类。
将[MapsTo]属性添加到源类,并使用目标类型作为参数。(或者,您可以使用[MapsFrom]属性将目标类与源类型进行映射。)
我已经完成了步骤1和步骤2,但无法理解如何以及在哪里使用步骤3:
这是我的模型类:
[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()扩展方法。我要从该程序集映射我的类型,如AutoMapper.Attributes文档的第三步中所建议。
我会在Controller中做(最终在构造函数中):
typeof(RoleViewModel).Assembly.MapTypes();
如果安装Automapper的版本4,则可以解决该问题,因为在最后一个版本中,属性不起作用。因此,请在Package-Manager控制台中添加以下说明:
uninstall-package Automapper
install-package Automapper -version 4.2.1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句