Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper Custom Mappings

Tags:

c#

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.

like image 801
N.K Avatar asked Nov 25 '13 15:11

N.K


People also ask

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

Does AutoMapper map private fields?

By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.

Can AutoMapper map enums?

Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.

What can I use instead of AutoMapper?

AutoMapper is one of the popular object-object mapping libraries with over 296 million NuGet package downloads. It was first published in 2011 and its usage is growing ever since. Mapster is an emerging alternative to AutoMapper which was first published in 2015 and has over 7.4 million NuGet package downloads.


1 Answers

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;
    }
));
like image 196
D Stanley Avatar answered Oct 20 '22 21:10

D Stanley