John S John S - 2 months ago 32
C# Question

Create AutoMapper mapping with calculated value?

I'm trying to configure a simple AutoMapper mapping from an Entity Framework entity to a view model object. It mostly works but in the view model I have an int field to hold a count. This field does not exist in the source entity.

cfg.CreateMap<Feed, FeedVM>()
.ForMember(dest => dest.Count, opt => opt.MapFrom(src => src.Orders.Count()));


When I check the validity of the mapping I get the following error message:


The following property on Feed cannot be mapped:

Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type Feed.
Context:
Mapping from type FeedVM to Feed


If I understand the Automapper syntax correctly I am mapping from Feed to FeedVM but the error message seems to indicate that I am mapping from FeedVM to Feed.

What should I be doing to map the value 42 to the Count field in FeedVM?

Answer

You should use ResolveUsing:

cfg.CreateMap<Feed, FeedVM>()
   .ForMember(dest => dest.Count, opt => opt.ResolveUsing(src => src.Orders.Count()));
Update

John indicates in the comment below that the mappings are correct, the problem lies in a mapping for another entity that is related to Feed. In that entity he is mapping both directions.

Comments