Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Conditional Mapping in AutoMapper?

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.

like image 666
Alwyn Avatar asked Jul 23 '13 23:07

Alwyn


People also ask

How do I use ForMember in AutoMapper?

CreateMap<EFAddress, Address>() . ForMember(dest => dest. Code, opt => opt. MapFrom(src => src.Name));

Why you should not use AutoMapper?

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 to list a map?

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.


2 Answers

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.

like image 185
TeeDee Avatar answered Sep 22 '22 15:09

TeeDee


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);             }) 
like image 41
Basim Avatar answered Sep 18 '22 15:09

Basim