Thiago M
Thiago M

Reputation: 191

How to map model property to view model using AutoMapper

Is there a simple way to map a single model property into a viewModel? I need to map some props from the "outter model" and the rest from the "inner model" (complex type)...

class Car
{
    public int Id {get;set;}
    public string Name {get;set;}
    public virtual CarDetails Details {get;set;}
}

class CarDetails
{
    public int Id {get;set;}
    public string Model {get;set;}
    public DateTime Year {get;set;}     
}

class DetailsViewModel
{
    public string Name {get;set;}
    public string Model {get;set;}
    public DateTime Year {get;set;}
}

Then I want to be able to:

var viewModel = mapper.Map<Car, DetailsViewModel>(car);

I've tried to map this without success using something like this:

CreateMap<Car, DetailsViewModel>().ForAllMembers(opts => opts.MapFrom(c => c.Details ));

PS¹.: I'm aware of the naming convetion for flattening objects, but in don't want to change the names of the view model and don't want to use multiple ForMember statements too (my current model is a lot bigger than the one from the example).

PS².: I'm using asp.net-core and a AutoMapperConfig static class to do all configuration. So I don't have access to the Mapper instance before registering the configurations.

Upvotes: 0

Views: 3217

Answers (1)

user3682091
user3682091

Reputation: 755

AutoMapper Config:

 var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Car, DetailsViewModel>()
                      .ForMember(x => 
                          x.Model, opt => opt.MapFrom(src => src.Details.Model))
                      .ForMember(x => 
                          x.Year, opt => opt.MapFrom(src => src.Details.Year));

        });

 var mapper = config.CreateMapper();

Then you can do

var detail = mapper.Map<Car, DetailsViewModel>(car);

Upvotes: 1

Related Questions