AutoMapper and ViewModel with equal fields

1

I have a Viewmodel ( UsuarioGrupoViewModel ) where I will show user and group data in the same View.

The problem is that both the User entity and the Group entity have the Name field, how do I handle this?

Note: I am using AutoMapper and my Viewmodels are in the application layer.

    
asked by anonymous 20.01.2016 / 15:03

1 answer

2

AutoMapper works to map a single class to another single class. So if in your ViewModel you will have information from a group and a user, I suggest you create a class that has a reference for each one. Something that will be instantiated like this:

var usuarioGrupo = new UsuarioGrupo 
{
    Usuario = usuario,
    Grupo = grupo
}

From there, I see two possibilities:

1) You will get your class UsuarioGrupoViewModel with references to two other ViewModel classes: UsuarioViewModel and GrupoViewModel . That is, to access the group name, you will search in usuarioGrupoViewModel.Grupo.Nome .

2) You can also create the GroupName and UserName fields and set a Profile of AutoMapper to fill in these fields, something like this:

Mapper.CreateMap<UsuarioGrupo, UsuarioGrupoViewModel>()
  .ForMember(d => d.NomeGrupo, o => o.MapFrom(s => s.Grupo.Nome))
  .ForMember(d => d.NomeUsuario, o => o.MapFrom(s => s.Usuario.Nome))
  .ReverseMap();

I often use both approaches.

    
29.06.2016 / 20:24