【问题标题】:AutoMapper does not work after upgrading 5.1.1升级 5.1.1 后 AutoMapper 不工作
【发布时间】:2017-01-24 23:37:27
【问题描述】:

对于我的 MVC 项目,我升级了我的 nuget 包并从 https://www.nuget.org/packages/AutoMapper/

它说支持 IList 作为映射源; https://github.com/AutoMapper/AutoMapper/wiki/Lists-and-arrays

它使用的是旧版本,我只更新了我的配置部分。

配置如下;

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {           
        AutoMapperConfig.RegisterMappings();            
    }
}

public static void RegisterMappings()
{
    Mapper.Initialize(cfg =>
    {
       cfg.CreateMap<RssNewDto, RssNewViewModel>();    
    });   
}   

// where I am trying to resolve
[HttpGet]
public IList<RssNewViewModel> ReadList()
{
     // EXCEPTION
    IList<RssNewViewModel> items2 = AutoMapper.Mapper.Map<IList<RssNewDto>, IList<RssNewViewModel>>(items);
    return items2;
}

错误:发生 AutoMapper.AutoMapperMappingException
HResult=-2146233088 消息=错误映射类型。内部异常: HResult=-2146233088 消息=缺少类型映射配置或 不支持的映射。

我在配置上遗漏了什么吗?

【问题讨论】:

  • 异常消息的其余部分是什么?它应该包括缺少的类型信息。
  • @JimmyBogard 在我调用 MapperConfiguration.AssertConfigurationIsValid 方法后,它清楚地向我显示了所有丢失的配置错误。我相信这个应该在 Initialize 方法之后在内部调用。由于人们可能忘记调用此方法,因此可能配置了无效的 Mapper,它会在运行时咬他们。
  • 哦,是的,我看到很多人都这样做。我不确定在生产中是否会这样做,但我认为我在那里是少数。

标签: c# automapper


【解决方案1】:

您的RegisterMappings 方法只是创建从RssNewDtoRssNewViewModel 的映射,而不是从IList&lt;RssNewDto&gt;IList&lt;RssNewViewModel&gt;

你可以这样做items.Select(item =&gt; AutoMapper.Mapper.Map&lt;RssNewViewModel&gt;(item)).ToList();

【讨论】:

  • 好吧.. 如果您查看文档,它会说“不需要显式配置列表类型,只需配置它们的成员类型”。我可能会尝试您的解决方案,但使用此库的方法似乎不正确。 github.com/AutoMapper/AutoMapper/wiki/Lists-and-arrays
  • 对,自动支持列表。
猜你喜欢
  • 1970-01-01
  • 2022-07-23
  • 2016-04-08
  • 2016-07-05
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
相关资源
最近更新 更多