Search code examples
c#asp.net-mvcautomapperpoco

Automapper error after updating a record with POCO classes, Unity and EF6


I've created an application that uses automapper, everything seems to be configured and working correctly in browse mode, however after I update a record I then get the following mapping error:

  AutoMapper.AutoMapperMappingException was unhandled by user code
  HResult=-2146233088
  Message=Missing type map configuration or unsupported mapping.
  Mapping types:
  Organisation -> ViewModelOrganisation

I've registered auttomapper in application start:

protected void Application_Start()
    {
        App_Start.AutoMapperConfig.Initialize();
    }

Then done the mapping in 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();
        });

    }

}

This hits OK when the application starts and I can browse the site. The problem occurs when I save a record (update). The information saves, however when I go back to another page to browse the site I get mapping errors.

Update:

Im mapping in the controller like so:

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);
    }

The error occurs on the line: vm = Mapper.Map(org, vm). It also occurs on other pages that use the mapper. But only after I have updated a record in my admin panel.


Solution

  • Prior to initializing the mapper in global.asa i was doing this in the controller itself. I had failed to remove the line(below), from the controller, where the article record was being edited:

     Mapper.Initialize(cfg => cfg.CreateMap<Article, ViewModelArticle>());
    

    This must have invalidated the mapping created on start up and hence my error when I went to browse the rest of the site.

    Lesson learned...Ensure to only initialise the mapper once!