自动映射丢失类型映射配置或不支持的映射

时间:2015-05-07 15:26:57

标签: entity-framework mongodb automapper repository-pattern nuget-package

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

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

如果我删除了作者属性,它就可以了。

有人可以帮助我,我错过了什么。感谢您阅读我的问题和我糟糕的英语。

1 个答案:

答案 0 :(得分:3)

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