6
I set up a project a while back, as follows, A Class called Automapperconfig as follows:
public class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.Initialize(x =>
{
x.AddProfile<DomainToViewModelMappingProfile>();
x.AddProfile<ViewModelToDomainMappingProfile>();
});
}
}
another class: DomainToViewModelMappingProfile mapping from Dominio to Viewmodel:
public class DomainToViewModelMappingProfile : Profile
{
public override string ProfileName
{
get { return "ViewModelToDomainMappings"; }
}
protected override void Configure()
{
Mapper.CreateMap<UsuarioViewModel, Usuario>();
}
}
and one that maps from Viewmodel to the Domain:
public class ViewModelToDomainMappingProfile : Profile
{
public override string ProfileName
{
get { return "DomainToViewModelMappings"; }
}
protected override void Configure()
{
Mapper.CreateMap<Usuario, UsuarioViewModel>();
}
}
And in the Controller Where I call a method where I get all users saved in the database
public ActionResult Index()
{
var UsuarioViewModel= Mapper.Map<IEnumerable<Usuario>, IEnumerable<UsuarioViewModel>>(_usuarioApp.ObterTodos());
return View(UsuarioViewModel);
}
And finally in the Global.asax made the call from AutoMapperConfig.RegisterMappings();
With that already worked perfectly the mapping for this context... But I saw that from version 4.2 Automapper this type of configuration is obsolete. How do I implement the framework in the new way ?
got the answer. Now speaking of the hint you gave about working directly with the User class, I did see in some implementations, where you have a Viewmodel class to validate with Dataannotations and do not need to reference them in the main class, thinks it’s best to do this directly in the User class ?
– user37440
@Renancarlos, completely unnecessary, the Framework has something much more appropriate and efficient:
How to: Add Metadata Classes
andEntity Framework Validation - IValidatableObject
– Tobias Mesquita