Automapper 缺少类型映射配置或不支持的映射

Automapper missing type map configuration or unsupported mapping

我有 2 个 class :

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

Class 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 个 class 具有相同的 属性。我尝试使用以下代码映射 2 class:

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

然后我收到一个错误:Automapper 缺少类型映射配置或不支持的映射。

如果我删除 Author 属性 ,它会起作用。

有人可以帮助我解决我所缺少的问题。感谢您阅读我的问题和我糟糕的英语。

您很可能缺少 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));
}