Suppose I have the following entities (classes)
public class Target { public string Value; } public class Source { public string Value1; public string Value2; }
Now I want to configure Auto Map, to Map Value1 to Value if Value1 starts with "A", but otherwise I want to map Value2 to Value.
This is what I have so far:
Mapper .CreateMap<Source,Target>() .ForMember(t => t.Value, o => { o.Condition(s => s.Value1.StartsWith("A")); o.MapFrom(s => s.Value1); <<***But then how do I supply the negative clause!?***>> })
However the part the still eludes me is how to tell AutoMapper to go take s.Value2
should the earlier condition fails.
It just seems to me the API was not designed as well as it could be... but may be it's my lack of knowledge getting in the way.
CreateMap<EFAddress, Address>() . ForMember(dest => dest. Code, opt => opt. MapFrom(src => src.Name));
1. If you use the convention-based mapping and a property is later renamed that becomes a runtime error and a common source of annoying bugs. 2. If you don't use convention-based mapping (ie you explicitly map each property) then you are just using automapper to do your projection, which is unnecessary complexity.
How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.
Try this
Mapper.CreateMap<Source, Target>() .ForMember(dest => dest.Value, opt => opt.MapFrom (src => src.Value1.StartsWith("A") ? src.Value1 : src.Value2));
Condition option is used to add conditions to properties that must be met before that property will be mapped and MapFrom option is used to perform custom source/destination member mappings.
AutoMapper allows adding conditions to properties that must be met before that property will be mapped.
Mapper.CreateMap<Source,Target>() .ForMember(t => t.Value, opt => { opt.PreCondition(s => s.Value1.StartsWith("A")); opt.MapFrom(s => s.Value1); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With