6

I am mapping between two objects, the source contains two strings called Animaland 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.

1
  • Can you post your class definitions Commented Jul 1, 2016 at 10:11

1 Answer 1

8

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>());
2
  • Thanks for the tip :) but I still get the same exception with ResolveUsing, which goes away if I add the unused <string, Pet> mapping
    – st3inn
    Commented Jul 1, 2016 at 9:45
  • 1
    @st3inn that's weird, but I suspect the error doesn't occur on the property you think then, as that member configuration should definitely work. Can you include further source code?
    – MarioDS
    Commented Jul 1, 2016 at 9:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.