我在映射复杂的嵌套对象时遇到问题。将集合AddressDto对象映射(添加)到BookDto对象时,AutoMapper崩溃。
public class Mapper : IMapper
{
public AutoMapper.IMapper Just { get; }
public Mapper()
{
Just = new AutoMapper.MapperConfiguration(config =>
{
config.CreateMap<Address, AddressDto>();
config.CreateMap<Book, BookDto>();
config.CreateMap<Author, AuthorDto>();
config.CreateMap<IEnumerable<AddressDto>, BookDto>()
.ForMember(bookDto => bookDto.Authors, authors => authors
.MapFrom(author => author));
.MapFrom(author => author));
})
.CreateMapper();
public T1Destination Map<T1Source, T1Destination, T2Source, T2Destination>(T1Source t1Source, T2Source t2Source)
{
var destination1 = Just.Map<T1Source, T1Destination>(t1Source);
var destination2 = Just.Map<T2Source, T2Destination>(t2Source);
return Just.Map<T2Destination, T1Destination>(destination2, destination1); // <-- Crash place
}
}
程序使用以下方法调用Map方法:
from book in books
select _mapper.Map<Book, BookDto, IEnumerable<Author>, IEnumerable<AuthorDto>>(
book,
(from association in associations
join author in authors
on association.AuthorId equals author.Id
where association.BookId == book.Id
select author).ToList()
);
图书班:
public class Book
{
// Some constructor
public string Title { get; protected set; }
public string Publisher { get; protected set; } // Kto opublikował (data)
public string Language { get; protected set; }
public int? Hardcover { get; protected set; } // Ilość stron
public string Binder { get; protected set; }
public decimal? Weight { get; protected set; }
public string Dimensions { get; protected set; }
public string ISBN { get; protected set; }
public string Type { get; protected set; }
public Guid Id { get; protected set; }
public string Description { get; protected set; }
public string Department { get; protected set; }
public decimal Price { get; protected set; }
public DateTime CreatedAt { get; protected set; }
public DateTime UpdateAt { get; protected set; }
}
BookDto类:
public class BookDto
{
public string Title { get; set; }
public string Publisher { get; set; }
public string Language { get; set; }
public int? Hardcover { get; set; }
public decimal? Weight { get; set; }
public string Dimensions { get; set; }
public string ISBN { get; set; }
public string Type { get; set; }
public decimal Price { get; set; }
public IEnumerable<AuthorDto> Authors { get; set; }
}
作者类:
public class Author
{
// Some constructor
public Guid Id { get; protected set; }
public string Name { get; protected set; }
public string Surname { get; protected set; }
}
AuthorDto类:
public class AuthorDto
{
public string Name { get; set; }
public string Surname { get; set; }
public IEnumerable<BookDto> ReleasedBooks { get; set; }
}
您能帮助我正确编写AutoMapper的配置还是找到更好的解决方案?