ebram khalil
ebram khalil

Reputation: 8321

AutoMapperMappingException when mapping different ViewModels to the same Model

I'm using Automapper to map my view models to my domain Models. In my case i have two ViewModels which i need to be mapped to the same Model.

I create two profiles foreach view model then in Mapper.Initialize i add them both. Then in my controller, when i try to map my ViewModel to the Model so i can pass it to a service i got this error Missing type map configuration or unsupported mapping.

My Code

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

Then in my controller:

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

Now if i removed the second profile CompanyActivateViewModelProfile i don't get any error and maping is done correctly. Any ideas on what I'm doing wrong?

Upvotes: 1

Views: 206

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46551

You are re-initializing AutoMapper by calling Mapper.Initialize twice causing the first profile to be removed. Try this:

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

Upvotes: 1

Related Questions