简体   繁体   中英

AutoMapper generic map method does not map enum values

I have a generic mapper function for mapping between View models and Domain models. For some reason, it does not map Enum values.

public TDomainModel MapToDomainModel<TViewModel, TDomainModel>(TViewModel viewModel)
{
    Mapper.CreateMap<TViewModel, TDomainModel>();
    TDomainModel result = Mapper.Map<TViewModel, TDomainModel>(viewModel);
    return result;
}

public TViewModel MapToViewModel<TDomainModel, TViewModel>(TDomainModel domainModel)
{
    Mapper.CreateMap<TDomainModel, TViewModel>();
    TViewModel result = Mapper.Map<TDomainModel, TViewModel>(domainModel);
    return result;
}

I need to map enum values to integers when mapping from view model to domain model. And map from integers to enum values when mapping from domain models to view models.

It would be great if the solution is flexible enough to convert from nullable enums to more types (short, byte etc) and vice versa.

using autofac mapper?

var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<TViewModel, TDomainModel>()
                 .ForMember(dest => dest.enumfield, opt => opt.MapFrom(src => (EnumFieldEnum)src.EnumField))               
                 .ReverseMap();
});


mapper = config.CreateMapper();

...`

var yy= mapper.Map<TDomainModel>(xx);

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