Automapper and Viewmodel with equal fields

Asked

Viewed 355 times

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 it?

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

  • Can post here the view model and entity code you are trying to map to?

  • Hello Felipe, I am responding from a machine that does not have the sources, but I need to show table data users and groups, the two tables have the NAME field, as I could create a viewmodel with these two equal fields?

1 answer

2


The AutoMapper works to map a single class into 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 of them. 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 name of the group, you will search in usuarioGrupoViewModel.Grupo.Nome.

2) You can also create the Group Name and User fields and configure a Profile of AutoMapper to fill these fields, with 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 usually use both approaches.

  • And how do I do this mapping? In the controller? In Viewmodel? Would you like to know where I do something like Mapper.Create(...)

  • 1

    You must create a class that you inherit from Automapper.Profile (e.g., Usersgroupomarprofile). In it, in your builder, you do the Createmap, as in the example of the answer. This class must be configured (it can be in Global.asax.Cs, in Application_start, for simplicity). There you do the Mapper.Initialize(cfg => { cfg.Addprofile<Usuariogrupomapperprofile>(); });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.