我有点新的AutoMapper,想要映射POCO十岁上下的对象也许是一个更复杂的DTO,后者试图成为的表示谷歌图书API的卷资源:
Book.cs
public class Book
{
public string Isbn10 { get; set; }
public string Isbn13 { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public DateTime Publication { get; set; }
public int Pages { get; set; }
public string Description { get; set; }
public bool InStock { get; set; }
}
BookDto.cs
public class BookDto
{
public string Kind { get; set; }
public string Id { get; set; }
public VolumeInfo VolumeInfo { get; set; }
}
public class VolumeInfo
{
public string Title { get; set; }
public List<string> Authors { get; set; }
public string Publisher { get; set; }
public string PublishedDate { get; set; }
public string Description { get; set; }
public int PageCount { get; set; }
public List<IndustryIdentifier> IndustryIdentifiers { get; set; }
}
public class IndustryIdentifier
{
public string Type { get; set; }
public string Identifier { get; set; }
}
因此,根据文档 ,我们可以简单地压平嵌套类型:
AutoMapperConfigurator.cs
public static class AutoMapperConfigurator
{
public static void Configure()
{
Mapper.CreateMap<Book, BookDto>()
.ForMember(dto => dto.Id, options => options.Ignore())
.ForMember(dto => dto.Kind, options => options.Ignore())
.ForMember(dto => dto.VolumeInfo.Title, options => options.MapFrom(book => book.Title))
.ForMember(dto => dto.VolumeInfo.Authors, options => options.MapFrom(book => book.Author.ToArray()))
.ForMember(dto => dto.VolumeInfo.Publisher, options => options.MapFrom(book => book.Publisher))
.ForMember(dto => dto.VolumeInfo.PublishedDate, options => options.MapFrom(book => book.Publication))
.ForMember(dto => dto.VolumeInfo.Description, options => options.MapFrom(book => book.Description))
.ForMember(dto => dto.VolumeInfo.PageCount, options => options.MapFrom(book => book.Pages))
;
}
}
但在运行时不幸Mapper.AssertConfigurationIsValid()
测试,我发现了以下错误:
System.ArgumentException:表达式“DTO => dto.VolumeInfo.Title”必须解析顶级成员,没有任何子对象的属性。 在子类型或代替AfterMap选项使用自定义解析。 参数名:lambdaExpression
所以,现在下面这个建议与AfterMap尝试:
public static class AutoMapperConfigurator
{
public static void Configure()
{
Mapper.CreateMap<Book, BookDto>()
.ForMember(dto => dto.Id, options => options.Ignore())
.ForMember(dto => dto.Kind, options => options.Ignore())
.AfterMap((book, bookDto) => bookDto.VolumeInfo = new VolumeInfo
{
Title = book.Title,
Authors = new List<string>(){ book.Author },
Publisher = book.Publisher,
PublishedDate = book.Publication.ToShortDateString(),
Description = book.Description,
PageCount = book.Pages
});
}
}
当再次运行测试,我现在得到这个消息:
未映射成员被发现。 查看下面的类型和成员。 添加自定义映射表达式,忽略,添加自定义解析,或修改源/目标类型预订 - > BookDto(目的地成员列表)Dotnet.Samples.AutoMapper.Book - > Dotnet.Samples.AutoMapper.BookDto(目的地成员列表) VolumeInfo
我应该创建嵌套类之间的附加映射? 任何指导将衷心感谢,感谢很多提前。