Alwyn Alwyn - 1 year ago 515
C# Question

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:

.ForMember(t => t.Value,
o =>
o.Condition(s =>
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
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.

Please help.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download