Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Lets assume I have the following classes

public class foo
{
    public string Value;
}


public class bar
{
    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<foo,bar>()
    .ForMember(t => t.Value, 
        o => 
            {
                o.Condition(s => 
                    s.Value1.StartsWith("A"));
                o.MapFrom(s => s.Value1);
                  <<***I want to throw Exception here***>>
            })

However I know how can I give value 1 or value 2 on Conditional basis but don't know how to put some custom code , call a function or throw an Exception

Please Guide.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
346 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can pass a lambda to ResolveUsing:

.ForMember(f => f.Value, o => o.ResolveUsing(b =>
    {
        if (b.Value1.StartsWith("A"))
        {
            return b.Value1;
        }
        return b.Value2;
    }
));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...