简体   繁体   中英

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.

As your full exception message says, the mapper doesn't have a mapping from Organisation to ViewModelOrganisation . I'm not sure, but is next to the reverse mapping not also a normal mapping needed? So try adding cfg.CreateMap<Organisation, ViewModelOrganisation>() .

Also you can simplify your code to this:

public ActionResult Detail(int id)
{
    var org = _orgService.getOrganisationByOrgID(id);
    var vm = Mapper.Map<ViewModelOrganisation>(org);
    return View(vm);
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM