Automapper missing type map configuration or unsupported mapping

时光总嘲笑我的痴心妄想 提交于 2019-12-12 21:25:04

问题


I have 2 class :

Class 1 : (Domain)

public class Book
{
    public ObjectId Id { get; set; }
    public String ISBN { get; set; }
    public String Title { get; set; }
    public String Publisher { get; set; }
    public int? PageCount { get; set; }
    public Author Author { get; set; }
}

Class 2 : (Repository)

public class Book
{        
    public ObjectId Id { get; set; }
    public String ISBN { get; set; }
    public String Title { get; set; }
    public String Publisher { get; set; }

    [BsonIgnoreIfNull]
    public int? PageCount { get; set; }
    public Author Author { get; set; }
}

For simple, i created 2 class have the same property. I tried to map 2 class with the code :

public static void SetAutoMapperConfiguration()
{
     Mapper.CreateMap<ME.Book.Book, DE.Book.Book>()
           .ForMember(dest => dest.PageCount, src => src.MapFrom(dest => dest.PageCount == null ? 0 : dest.PageCount))
           .ForMember(dest => dest.Author, src => src.MapFrom(dest => dest.Author == null ? null : dest.Author));
}

Insert method :

public async Task InsertBook(DE.Book book)
    {
        try
        {
            var bookCollections = GetDatabase().GetCollection<Book>(MongoCollection);
            Book savedBook = new Book(book.ISBN, book.Title, book.Publisher,
                new Author { FirstName = book.Author.FirstName, LastName = book.Author.LastName });

            Mapper.Map(savedBook, book); //Map failed
            await bookCollections.InsertOneAsync(savedBook);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.GetBaseException());
        } 
    }

Then i got an error : Automapper missing type map configuration or unsupported mapping.

In case i remove Author property , it worked.

Can someone help me what i missing. Thanks for your reading my question and my poor English.


回答1:


You are most probably missing configuration for Author classes. I assume, you also have ME.Book.Author and DE.Book.Author, so you have to provide configure mapping also between these two classes.

Extend configuration like this:

public static void SetAutoMapperConfiguration()
{
    // fix namespaces and optionally provide mapping between properties
    Mapper.CreateMap<ME.Book.Author, DE.Book.Author>();    

    Mapper.CreateMap<ME.Book.Book, DE.Book.Book>()
           .ForMember(dest => dest.PageCount, src => src.MapFrom(dest => dest.PageCount == null ? 0 : dest.PageCount))
           .ForMember(dest => dest.Author, src => src.MapFrom(dest => dest.Author == null ? null : dest.Author));
}


来源:https://stackoverflow.com/questions/30105479/automapper-missing-type-map-configuration-or-unsupported-mapping

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