mapping strings into object of same name

I am mapping between two objects, the source contains two strings called Animal and AnimalColor , for instance Animal = "Cat" and AnimalColor = "White" . The destination contains a property Animal which is a class of type Pet which contains two strings, Type And Color

Therefore I have the following in my mapper configuration:

cfg.CreateMap<SrcPetStore, DestPetStore>()
    .ForMember(dest => dest.Animal, opt => opt.MapFrom(src => new Pet() { Type = src.Animal, Color = src.AnimalColor }));

When I run this I get an AutoMapperMappingException complaining about Missing type map configuration or unsupported mapping on mapping String -> Pet

It's like it tries to map the destination Animal (Pet object) from the source Animal (string) without taking the custom ForMember configuration into account

If I add an unused mapping cfg.CreateMap<string, Pet>() everything works but it shouldn't be necessary since that mapping is never used (and makes no sense)

This is in AutoMapper 5.0.


MapFrom() is used to simply select the source property for mapping. It's basically telling AutoMapper "I want you to take this property name to map to this property name, but map the types using type mappings that you have in your configuration.

It is documented as Projection.

What you are trying to do is known as Custom value resolution. Use the ResolveUsing method like this (simply replace MapFrom ):

.ForMember(dest => dest.Animal, opt => opt.ResolveUsing(src => new Pet() { Type = src.Animal, Color = src.AnimalColor }));

ResolveUsing literally returns whatever your function returns and assigns it to the destination property, without trying to do any additional maps.

You can also create a ValueResolver class and use it like this:

.ForMember(dest => dest.Animal, opt => opt.ResolveUsing<PetResolver>());
链接地址: http://www.djcxy.com/p/37376.html

上一篇: AutoMapper Map和带有列表的拼合实体

下一篇: 将字符串映射到同名的对象中