自动应用程序缺少类型地图配置或不支持的映射



我有2个类:

类1 :(域)

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; }
}

第2类:(存储库)

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; }
}

为了简单,我创建了2类具有相同的属性。我尝试用代码映射2个类:

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));
}

插入方法:

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());
        } 
    }

然后我有一个错误:自动应用程序缺少类型地图配置或不支持的映射。

如果我删除作者属性,则有效。

有人可以帮助我我想念的东西。感谢您阅读我的问题和不良的英语。

您很可能缺少Author类的配置。我认为,您也有ME.Book.AuthorDE.Book.Author,因此您还必须在这两个类之间提供配置映射。

这样扩展配置:

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));
}