Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper error on simple conversion without CreateMap

I have these 2 models:

public class SiteSettingsViewModel
{
    public decimal SubscriptionFee { get; set; }
}

public class SiteSettings
{
    public decimal SubscriptionFee { get; set; }
}

and the code:

var model = Mapper.Map<SiteSettings, SiteSettingsViewModel>(settingService.GetSettings());

Which throws the error of:

Trying to map WebApp1.Domain.Site.SiteSettings to WebApp1.WebUI.ViewModel.SiteSettingsViewModel. Missing type map configuration or unsupported mapping. Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.

Why do I need to put the code:

Mapper.CreateMap<SiteSettings, SiteSettingsViewModel>();

To me, this seems like I'm writing monkey code. This is not needed.

Why didn't the 1 line work?

like image 942
Shawn Mclean Avatar asked Nov 15 '22 00:11

Shawn Mclean


1 Answers

One reason is that it's useful for more complex mapping scenarios where you need to define more specific behaviors. For example (from CodePlex):

Mapper.CreateMap<CalendarEvent, CalendarEventForm>()
    .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date))
    .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour))
    .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute));

Another option for simple mapping like what you're doing is to make a generic mapper that takes care of the CreateMap call for you, like this:

public interface IMapper<T1, T2>
{   
    T1 Map(T2 source);
}

public class Mapper<T1, T2> : IMapper<T1, T2> where T1 : class where T2 : class
{
    public Mapper()
    {
        Mapper.CreateMap<T2, T1>();
    }

    public T1 Map(T2 source)
    {
        return Mapper.Map<T2, T1>(source);
    }   
}

And then you can just instantiate them directly like:

var mapper = new Mapper<SiteSettings, SiteSettingsViewModel>();

Or register them to be injected into your controllers, or wherever else you plan on using them. Hope that helps.

like image 114
ataddeini Avatar answered Dec 26 '22 00:12

ataddeini