[英]Automapper error after updating a record with POCO classes, Unity and EF6
我創建了一個使用自動映射器的應用程序,所有內容似乎都已配置並且可以在瀏覽模式下正常工作,但是在更新記錄后,我得到了以下映射錯誤:
AutoMapper.AutoMapperMappingException was unhandled by user code
HResult=-2146233088
Message=Missing type map configuration or unsupported mapping.
Mapping types:
Organisation -> ViewModelOrganisation
我已經在應用程序啟動中注冊了auttomapper:
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)。 它也發生在使用映射器的其他頁面上。 但只有在我更新了管理控制台中的記錄后,才可以。
如您的完整異常消息所述,映射器沒有從Organisation
到ViewModelOrganisation
的映射。 我不確定,但是在反向映射旁邊還不需要法線映射嗎? 因此,請嘗試添加cfg.CreateMap<Organisation, ViewModelOrganisation>()
。
您也可以將代碼簡化為:
public ActionResult Detail(int id)
{
var org = _orgService.getOrganisationByOrgID(id);
var vm = Mapper.Map<ViewModelOrganisation>(org);
return View(vm);
}
在global.asa中初始化映射器之前,我是在控制器本身中執行此操作的。 我未能從正在編輯文章記錄的控制器中刪除行(下方):
Mapper.Initialize(cfg => cfg.CreateMap<Article, ViewModelArticle>());
這一定會使啟動時創建的映射無效,因此,當我去瀏覽站點的其余部分時出現了我的錯誤。
經驗教訓...確保僅初始化一次映射器!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.