Automapper how to implement correctly

1

I am using automapper 7 but the documentation of this version is not very explicit I have implemented in this way.

1) I declare at the class level.

private MapperConfiguration _config;

2) Implement in this way to map from one entity to another.

public void Creado(ProductoCatalogoExtend entity)
    {
        _config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<ProductoCatalogoExtend, ProductoCatalogo>();
        });
        var mapper = _config.CreateMapper();
        var dto = mapper.Map<ProductoCatalogo>(entity);
        _sdProductoCatalogo.Create(dto);
    }

I think this implementation can be improved, I think you can use less lines of code.

I do not find the documentation of this version very much Automapper other versions They had good documentation on Github and there were better examples.

Greetings!

  

Note: It is a Windows Forms app, I do not use any design pattern.

    
asked by Pedro Ávila 17.10.2018 в 22:12
source

1 answer

1

A simple way to use AutoMapper is to create a static configuration that loads in Main of Program.cs before Application.Run

I'll leave an example mapping a Person to PersonaViewModel class:

public class Persona
{
    public int Id { get; set; }
    public string Nombre { get; set; }
    public string Apellido { get; set; }
    public DateTime FechaNacimiento { get; set; }
}

public class PersonaViewModel
{
    public int Id { get; set; }
    public string NombreCompleto { get; set; }
    public int Edad { get; set; }

}


static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        // configuracion estatica de automapper
        AutoMapperConfiguration.Configure();

        Application.Run(new Form1());
    }
}

AutoMapperConfiguration:

public static class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<MappingProfile>();
        });
        Mapper.AssertConfigurationIsValid();
    }
}

MappingProfile:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Persona, PersonaViewModel>()
            .ForMember(dest => dest.NombreCompleto, opt => opt.MapFrom(src => $"{src.Nombre} { src.Apellido }"))
            .ForMember(dest => dest.Edad, opt => opt.MapFrom(src => DateTime.Now.Year - src.FechaNacimiento.Year));
    }
}

The use would be summarized in a single line of code:

var persona = new Persona
{
    Id = 78,
    Nombre = "Fulanito",
    Apellido = "De tal",
    FechaNacimiento = new DateTime(1985, 1, 1)
};

var personaViewModel = Mapper.Map<PersonaViewModel>(persona);

Greetings, I hope you serve

    
answered by 18.10.2018 / 05:50
source