开发者

Automapper - setting a custom type convertor for a member

开发者 https://www.devze.com 2023-02-22 05:28 出处:网络
Lets have two classes public class Source { public string Prop1 {get;set;} } public class Dest { publi开发者_如何学Cc float Prop1 {get;set;}

Lets have two classes

public class Source
{
     public string Prop1 {get;set;}
}

public class Dest
{
     publi开发者_如何学Cc float Prop1 {get;set;}
}

How to set a custom type convertor for Prop1 property ?

Mapper.CreateMap<Source, Dest>()


You can use ConvertUsing as described in the docs. For that you need to define a Converter. Or you can define the mapping:

class Program
{
    static void Main(string[] args)
    {
        AutoMapper.Mapper.CreateMap<Source, Dest>()
            .ForMember(
                dest => dest.Prop1,
                src => src.MapFrom(m => float.Parse(m.Prop1, System.Globalization.CultureInfo.InvariantCulture)
            ));
        Source sourceObject = new Source() { Prop1 = "1.5" };
        Dest destination = AutoMapper.Mapper.Map<Source, Dest>(sourceObject);
        Console.WriteLine("value {0}", destination.Prop1);
    }
}

public class Source
{
    public string Prop1 { get; set; }
}

public class Dest
{
    public float Prop1 { get; set; }
}


May be it will be better just to map the object manually.

about custom mapping you can read here

0

精彩评论

暂无评论...
验证码 换一张
取 消