【发布时间】:2018-12-13 12:06:03
【问题描述】:
我创建了一个使用自动映射器的应用程序,一切似乎都已配置并在浏览模式下正常工作,但是在我更新记录后,我收到以下映射错误:
AutoMapper.AutoMapperMappingException was unhandled by user code
HResult=-2146233088
Message=Missing type map configuration or unsupported mapping.
Mapping types:
Organisation -> ViewModelOrganisation
我已经在应用程序启动中注册了自动映射器:
protected void Application_Start()
{
App_Start.AutoMapperConfig.Initialize();
}
然后在 Automapperconfig 中完成映射:
public class AutoMapperConfig
{
public static void Initialize()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Organisation, ViewModelOrganisation>().ReverseMap();
cfg.CreateMap<Article, ViewModelArticle>().ReverseMap();
cfg.CreateMap<Organisation, ViewModelAdminOrg>().ReverseMap();
cfg.CreateMap<Branch, ViewModelBranch>().ReverseMap();
});
}
}
当应用程序启动并且我可以浏览该站点时,这会点击确定。当我保存记录(更新)时会出现问题。信息会保存,但是当我返回另一个页面浏览该站点时,我会遇到映射错误。
更新:
我像这样在控制器中映射:
public ActionResult Detail(int id)
{
Organisation org = new Organisation();
ViewModelOrganisation vm = new ViewModelOrganisation();
org = _orgService.getOrganisationByOrgID(id);
vm = Mapper.Map(org, vm);
return View(vm);
}
错误发生在一行:vm = Mapper.Map(org, vm)。它也出现在使用映射器的其他页面上。但只有在我更新了管理面板中的记录之后。
【问题讨论】:
-
这不是完整的错误信息。请发布完整的例外。可能您缺少从源类型到目标类型的映射,必须将其添加到您的初始化方法中。初始化时也不会抛出这个错误,它会在 AutoMapper 尝试从 type a 转换为 type b 时抛出。
-
如果您不知道此异常发生的位置,请在 Visual Studio 中启动您的应用程序。在 Visual Studio Debug - Window - Exception Settings 中打开并启用第二个选项 Common Language Runtime Exception 的复选框。然后您的调试器将在引发此异常的位置停止。
-
@Oliver 错误在 vm = Mapper.Map(org, vm);在控制器中,但是我认为这不是问题,因为它仅在使用实体框架进行更新后才停止工作?
标签: c# asp.net-mvc automapper poco