How to Configure AutoMapper Attributes in ASP.NET MVC

空扰寡人 提交于 2019-12-24 08:38:19

问题


According to the GitHUb documentation, To use AutoMapper.Attributes need three steps to be done as follows:

  1. Create the classes you'd like to map.

  2. 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.)

  3. Call the MapTypes() extension method on the assembly from which you want to map your types.

I have done the step 1 and step 2 but can not understand how to and where to use the step 3:

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; }
}

And Here is my Controller Method:

public ActionResult Index()
{
    List<ApplicationRole> applicationRoles = RoleManager.Roles.ToList();
    List<RoleViewModel> roleList = Mapper.Map<List<RoleViewModel>>(applicationRoles);  
    return View(roleList);
}

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.


回答1:


I would do in the Controller (eventually in the constructor):

 typeof(RoleViewModel).Assembly.MapTypes();

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


来源:https://stackoverflow.com/questions/40231494/how-to-configure-automapper-attributes-in-asp-net-mvc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!