AutoMapper flattening of nested mappings asks for a custom resolver

有些话、适合烂在心里 提交于 2019-12-04 23:42:28

I've done something similar before using .ForMember with an internal mapping for the VolumnInfo mapping:

public static class AutoMapperConfigurator
{
    public static void Configure()
    {
        Mapper.CreateMap<Book, VolumeInfo>()
            .ForMember(dto => dto.Authors, options => options.MapFrom(book => book.Author.Split(',')))
            .ForMember(dto => dto.PublishedDate, options => options.MapFrom(book => book.Publication))
            .ForMember(dto => dto.PageCount, options => options.MapFrom(book => book.Pages))
            .ForMember(dto => dto.IndustryIdentifiers, options => options.Ignore());

        Mapper.CreateMap<Book, BookDto>()
            .ForMember(dto => dto.Id, options => options.Ignore())
            .ForMember(dto => dto.Kind, options => options.Ignore())
            .ForMember(dto => dto.VolumeInfo, options => options.MapFrom(book => Mapper.Map<Book, VolumeInfo>(book)));
    }
}

Here are a couple of unit tests that verify the functionality:

[TestFixture]
public class MappingTests
{
    [Test]
    public void AutoMapper_Configuration_IsValid()
    {
        AutoMapperConfigurator.Configure();
        Mapper.AssertConfigurationIsValid();
    }

    [Test]
    public void AutoMapper_MapsAsExpected()
    {
        AutoMapperConfigurator.Configure();
        Mapper.AssertConfigurationIsValid();

        var book = new Book
            {
                Author = "Castle,Rocks",
                Description = "Awesome TV",
                InStock = true,
                Isbn10 = "0123456789",
                Isbn13 = "0123456789012",
                Pages = 321321,
                Publication = new DateTime(2012, 11, 01),
                Publisher = "Unknown",
                Title = "Why I Rock"
            };

        var dto = Mapper.Map<Book, BookDto>(book);

        Assert.That(dto.Id, Is.Null);
        Assert.That(dto.Kind, Is.Null);
        Assert.That(dto.VolumeInfo, Is.Not.Null);
        Assert.That(dto.VolumeInfo.Authors, Is.Not.Null);
        Assert.That(dto.VolumeInfo.Authors.Count, Is.EqualTo(2));
        Assert.That(dto.VolumeInfo.Authors[0], Is.EqualTo("Castle"));
        Assert.That(dto.VolumeInfo.Authors[1], Is.EqualTo("Rocks"));
        Assert.That(dto.VolumeInfo.Description, Is.EqualTo("Awesome TV"));
        Assert.That(dto.VolumeInfo.IndustryIdentifiers, Is.Null);
        Assert.That(dto.VolumeInfo.PageCount, Is.EqualTo(321321));
        Assert.That(dto.VolumeInfo.PublishedDate, Is.EqualTo(new DateTime(2012, 11, 01).ToString()));
        Assert.That(dto.VolumeInfo.Publisher, Is.EqualTo("Unknown"));
        Assert.That(dto.VolumeInfo.Title, Is.EqualTo("Why I Rock"));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!