传统的AutoMap需要给每一个转换定义规则,如果有很多实体就会很麻烦,所以做了一个扩展类用来简化步骤
使用
实体1 的结果. MapTo < 实体2> ( ) ;
public class User
{ public int Id { get ; set ; }
}
public class UserDto
{ public int Id { get ; set ; }
}
var user= new User ( ) { Id= 1 } ;
user. MapTo < UserDto> ( ) ;
user. MapTo < User, UserDto> ( opts =>
{ opts. BeforeMap ( ( src, dest) => { dest. Id = src. Id; } ) ; opts. AfterMap ( ( src, dest) => { dest. Id = src. Id; } ) ;
} ) ;
扩展类
using AutoMapper ;
using System. Collections. Concurrent ; namespace Easy. Common. Core
{ public static class AutoMapperExtensions { private static readonly ConcurrentDictionary< string , IMapper> MapperCache = new ConcurrentDictionary< string , IMapper> ( ) ; private static IMapper GetOrCreateMapper ( Type sourceType, Type destinationType) { var key = $" { sourceType. FullName } _ { destinationType. FullName } " ; if ( ! MapperCache. TryGetValue ( key, out var mapper) ) { var config = new MapperConfiguration ( cfg => { cfg. CreateMap ( sourceType, destinationType) ; } ) ; mapper = config. CreateMapper ( ) ; MapperCache[ key] = mapper; } return mapper; } public static TDestination MapTo < TDestination> ( this object source) { var mapper = GetOrCreateMapper ( source. GetType ( ) , typeof ( TDestination ) ) ; return mapper. Map < TDestination> ( source) ; } public static List< TDestination> MapListTo < TSource, TDestination> ( this object source) { var mapper = GetOrCreateMapper ( source. GetType ( ) , typeof ( TDestination ) ) ; return mapper. Map < List< TDestination> > ( source) ; } public static TDestination MapTo < TSource, TDestination> ( this TSource source, Action< IMappingOperationOptions< TSource, TDestination> > opts) { var mapper = GetOrCreateMapper ( typeof ( TSource ) , typeof ( TDestination ) ) ; return mapper. Map ( source, opts) ; } }
}