0
votes

I'm using auto mapper to map from a view model to dto. Below are some test examples.

public class Vehicle
{
    public Vehicle()
    {
        AboutYou = new AboutYou();
        TestModels = new List<TestModel>();
    }

    public AboutYou AboutYou { get; set; }

    public List<TestModel> TestModels { get; set; }
}

public class AboutYou
{
    [DisplayName("What is your title")]
    public int Title { get; set; }
}

public class TestModel
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}

And Dto.

public class TestModel
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}

public class VehicleDto
{
    public VehicleDto()
    {
        TestDtos = new List<TestDto>();
    }

    public int AboutYouTitle { get; set; }

    public List<TestDto> TestDtos { get; set; }
}

public class TestDto
{
    public string FirstName { get; set; }

    public string Surname { get; set; }
}

And this is my profile.

public class VehicleMapping : Profile
{
    public VehicleMapping()
    {          
        CreateMap<Vehicle, VehicleDto>().ReverseMap();
        CreateMap<TestModel, TestDto>().ReverseMap();          

    }        
}

The problem I'm having is that I need to have the reversemap in place so it flattens and unflattens the AboutYou class. However, the TestModels collection is not being mapped to the TestDtos collection. I can apply a AfterMap but then I have to manually unflatten the AboutYou object. Any ideas how I can set it up so that the AboutYou is flattened and unflattened and the collections are mapped as well?

1

1 Answers

2
votes

Specifying how to map members explicitly did the trick for me

public class VehicleMapping : Profile
{
    public VehicleMapping()
    {
        CreateMap<Vehicle, VehicleDto>()
            .ForMember(x => x.TestDtos, opt => opt.MapFrom(src => src.TestModels))          
            .ReverseMap();
        CreateMap<TestModel, TestDto>().ReverseMap();

    }
}