TanvirArjel
TanvirArjel

Reputation: 32069

How to Configure AutoMapper Attributes in ASP.NET MVC

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.

Upvotes: 1

Views: 709

Answers (1)

meJustAndrew
meJustAndrew

Reputation: 6613

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

Upvotes: 1

Related Questions