漂泊雪狼的博客

思考,讨论,分享C#,JavaScript,.NET,Oracle,SQL Server……技术

导航

AutoMapper的使用

Posted on 2017-06-04 12:27  漂泊雪狼  阅读(3668)  评论(0编辑  收藏  举报

常规的使用,一般先初始化配置,一个应用只需初始化一次

 Mapper.Initialize(cfg => cfg.CreateMap<Order, OrderDto>());
    //or
    var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());
var mapper = config.CreateMapper();
// or
var mapper = new Mapper(config);
OrderDto dto = mapper.Map<OrderDto>(order);
// or
OrderDto dto = Mapper.Map<OrderDto>(order);

使用AutoMapper进行Entity与DTO之间的转换,不同字段之间的映射转换

 AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<StreetEvent, StreetEventDTO>()
            .ForMember(dest => dest.EvtSrc, opt => opt.MapFrom(src => src.evt_src))
            .ForMember(dest => dest.MapId, opt => opt.MapFrom(src => src.map_id))
            );

            var targetList = AutoMapper.Mapper.Map<List<StreetEventDTO>>(list);

实体之间的自定义类型转换,参考:

https://github.com/AutoMapper/AutoMapper/wiki/Custom-type-converters

   public class Source
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
        public string Value3 { get; set; }
    }

  public class Destination
    {
        public int Value1 { get; set; }
        public DateTime Value2 { get; set; }
        public Type Value3 { get; set; }
    }

[Test]
    public void Example()
    {
        Mapper.Initialize(cfg => {
          cfg.CreateMap<string, int>().ConvertUsing(Convert.ToInt32);
          cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
          cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();
          cfg.CreateMap<Source, Destination>();
        });
        Mapper.AssertConfigurationIsValid();
    
        var source = new Source
        {
            Value1 = "5",
            Value2 = "01/01/2000",
            Value3 = "AutoMapperSamples.GlobalTypeConverters.GlobalTypeConverters+Destination"
        };
        
        Destination result = Mapper.Map<Source, Destination>(source);
        result.Value3.ShouldEqual(typeof (Destination));
    }
    
    public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
    {
        public DateTime Convert(string source, DateTime destination, ResolutionContext context)
        {
            return System.Convert.ToDateTime(source);
        }
    }
    
    public class TypeTypeConverter : ITypeConverter<string, Type>
    {
        public Type Convert(string source, Type destination, ResolutionContext context)
        {
              return context.SourceType;
        }
    }

自定义实体值的转换,适用于目标与源实体直接的值类型计算,参考

https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers

public class Source
    {
        public int Value1 { get; set; }
        public int Value2 { get; set; }
    }
    
    public class Destination
    {
        public int Total { get; set; }
    }

  public class CustomResolver : IValueResolver<Source, Destination, int>
    {
        public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
        {
            return source.Value1 + source.Value2;
        }
    }

Mapper.Initialize(cfg => 
       cfg.CreateMap<Source, Destination>()
         .ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolver>());
    Mapper.AssertConfigurationIsValid();
    
    var source = new Source
        {
            Value1 = 5,
            Value2 = 7
        };
    
    var result = Mapper.Map<Source, Destination>(source);
    
    result.Total.ShouldEqual(12);
public class MultBy2Resolver : IValueResolver<object, object, int> {
    public int Resolve(object source, object dest, int destMember, ResolutionContext context) {
        return destMember * 2;
    }
}

  Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>()
        .ForMember(dest => dest.Total, 
            opt => opt.ResolveUsing(new CustomResolver())
        );



Mapper.Initialize(cfg => {
cfg.CreateMap<Source, Destination>()
    .ForMember(dest => dest.Total,
        opt => opt.ResolveUsing<CustomResolver, decimal>(src => src.SubTotal));
cfg.CreateMap<OtherSource, OtherDest>()
    .ForMember(dest => dest.OtherTotal,
        opt => opt.ResolveUsing<CustomResolver, decimal>(src => src.OtherSubTotal));
});

public class CustomResolver : IMemberValueResolver<object, object, decimal, decimal> {
    public decimal Resolve(object source, object destination, decimal sourceMember, decimal destinationMember, ResolutionContext context) {
// logic here
    }
}