10

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.

1 Answer 1

21

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;
    }
));
Sign up to request clarification or add additional context in comments.

6 Comments

I don't want to give the reference to memory so I cant use ResolveUsing , is there any option to use the same thing with MapFrom ?
What do you mean by "give the reference to memory"?
ResolveUsing uses the Reference where as MapFrom uses the Value of the property being mapped.
I'm still not sure I understand - MapFrom is designed to map straight from properties (it still pulls the value from the reference to the object being mapped from), while ResolveUsing is designed to allow virtually any mapping logic.
there is a mistake in "if (b.Value1.StartsWith("A"));)". (excessive symbols in the end)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.