【问题标题】:AutoMapperMappingException when mapping different ViewModels to the same Model将不同的 ViewModel 映射到同一个 Model 时出现 AutoMapperMappingException
【发布时间】:2018-05-16 11:50:25
【问题描述】:

我正在使用 Automapper 将我的视图模型映射到我的域模型。就我而言,我有两个 ViewModel 需要映射到同一个模型。

我为每个视图模型创建两个配置文件,然后在Mapper.Initialize 中添加它们。然后在我的控制器中,当我尝试将我的 ViewModel 映射到模型以便我可以将它传递给服务时,我收到了这个错误Missing type map configuration or unsupported mapping.

我的代码

public static class AutoMapperWebConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(cfg => cfg.AddProfile(new CompanyRegisterViewModelProfile()));
            Mapper.Initialize(cfg => cfg.AddProfile(new CompanyActivateViewModelProfile()));
        }
    }

然后在我的控制器中:

CompanyEmployee CompanyEmployee = Mapper.Map<CompanyRegisterViewModel, CompanyEmployee>(model,);

现在,如果我删除了第二个配置文件 CompanyActivateViewModelProfile,我不会收到任何错误,并且映射已正确完成。关于我做错了什么有什么想法吗?

【问题讨论】:

  • 作为建议,请在 Configure 中调用 Mapper.AssertConfigurationIsValid - 然后 automapper 在启动时抛出错误,而不是在首次使用时抛出错误。

标签: c# asp.net-mvc-5 automapper


【解决方案1】:

您正在通过调用 Mapper.Initialize 两次重新初始化 AutoMapper,导致第一个配置文件被删除。试试这个:

Mapper.Initialize(cfg => 
    {
        cfg.AddProfile(new CompanyRegisterViewModelProfile());
        cfg.AddProfile(new CompanyActivateViewModelProfile());
    });

【讨论】:

  • 没错。当我在寻找解决方案时,我注意到我不止一次调用Initialize,而我应该将配置文件作为列表传递。连续工作 10 小时会发生这种情况
  • 还有,cfg.AddProfile;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
相关资源
最近更新 更多