Entity core Mapping entity types with join table

强颜欢笑 提交于 2019-12-06 23:07:25

Here is the desired mapping configuration:

CreateMap<Book, BookViewModel>()
    // Book -> BookViewModel
    .ForMember(b => b.Authors, opt => opt.MapFrom(b => b.BookAuthors
        .Select(ba => ba.Author)))
    .ReverseMap()
    // BookViewModel -> Book
    .PreserveReferences()
    .ForMember(b => b.BookAuthors, opt => opt.MapFrom(b => b.Authors
        .Select(a => new { b.BookId, Book = b, a.AuthorId, Author = a })))
    ;

CreateMap<Author, AuthorViewModel>()
    // Author -> AuthorViewModel
    .ReverseMap()
    // AuthorViewModel -> Author
    ;

The most important thing is to realize that AutoMapper does not require the type of the returned expression from MapFrom to match the type of the destination. If it doesn't match, then AutoMapper will try to map the returned type to the destination type using the corresponding mapping if any. This allows you to reuse the mappings.

In order to convert BookAuthor to AuthorViewModel, you first convert it to Author (by simply extracting the Author property) like if it was a collection of Author, and let AM convert the Author to AuthorViewModel using the corresponding mapping.

In order to convert AuthorViewModel from BookViewModel.Authors to BookAuthor, you convert it first to anonomymous type similar to BookAuthor, but with corresponding Book and Author property types being ViewModel types and let AM convert it to BookAuthor using corresponding mappings. PreserveReferences() is used to avoid stack overflow due to circular reference model.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!