Automapper Mapping

2019-01-20 05:30发布

I'm trying to map an object with property names like so:

Property_One -> PropertyOne ... etc
Sample_Property -> SampleProperty

Is there a better way to do this than to map individually each property to another? The only difference is the underline.

2条回答
The star\"
2楼-- · 2019-01-20 05:50
public class Source
{
    public string Property_One { get; set; }
}

public class Dest
{
    public string PropertyOne { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Mapper.CreateMap<Source, Dest>()
            .ForMember(dest => dest.PropertyOne,
                       opt => opt.MapFrom(src => src.Property_One));

        var source = new Source
        {
            Property_One = "property1"
        };

        var destination = Mapper.Map<Source, Dest>(source);
        Console.WriteLine(destination.PropertyOne);
    }
}
查看更多
放我归山
3楼-- · 2019-01-20 06:15

You'll need to specify the underscore naming convention on the source side:

Mapper.Initialize(i => 
{
    i.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
    i.CreateMap<Source, Dest>(); 
});

You can do that globally (as shown above) or per Profile, if only some of your source types follow this naming convention.

查看更多
登录 后发表回答