首页 > 解决方案 > 为什么AutoMapper按照文档实现时会抛出异常?

问题描述

我尝试在 ASP.NET MVC 应用程序中使用 AutoMapper,但是当我查看详细信息时,无法让这个 AutoMapper 停止使用 AutoMapperConfigurationExceptions 打击我,AutoMapper 基本上告诉我它无法映射任何属性,即。找不到个人资料?!?

我已经根据 AutoMapper 网站上的文档完成了所有工作。

全球.asax:

protected void Application_Start()
{
    // neither of those two ways works
    Mapper.Initialize(cfg => cfg.AddProfiles(typeof(ImageEntity2GalleryModelMapping)));
    Mapper.Initialize(cfg => cfg.AddProfiles(Assembly.GetExecutingAssembly()));
}

映射配置文件:

public class ImageEntity2GalleryModelMapping : Profile
{
    // take note that this used to be an override of Configure() but the
    // AutoMapper API has changed recently to favor Ctor now
    public ImageEntity2GalleryModelMapping()
    {
        CreateMap<Image, GalleryModel>()
            .ForMember(dest => dest.ImageId, opt => opt.MapFrom(src => src.ImageId))
            // and so on
            ;
    }
}

控制器内部:

public ActionResult Index()
{
    return View(Mapper.Map<GalleryModel>(_dbContext.Images.ToList()));
}

我错过了什么吗?

标签: c#asp.net-mvcautomapper

解决方案


好的,刚刚发现,我确实需要映射到一个集合类(我的印象是 AutoMapper 隐含地处理了这个)。

只是从这里改变

return View(Mapper.Map<GalleryModel>(_dbContext.Images));

对此

return View(Mapper.Map<IList<GalleryModel>>(_dbContext.Images));

现在它可以工作了;)


推荐阅读