简体   繁体   中英

How to Get Mapper by BaseType

I want to get commented mapper(AutoMapper.Mapper.FindTypeMapFor) by using base type.

Is it possible to get it like in the usage

        AutoMapper.Mapper.CreateMap<IEntity, ListItemModelBase>()
            .Include<Book, BookListItemModel>();

        AutoMapper.Mapper.CreateMap<Book, BookListItemModel>()              
            .ForMember(  a => a.Author, (a) => a.MapFrom( entity => entity.Author.Name))
            .ForMember(a => a.Genre, (a) => a.MapFrom( entity => entity.Genre.Name));


        AutoMapper.Mapper.CreateMap<BookListItemModel, Book>();

        AutoMapper.Mapper.CreateMap<BookFormModel, Book>()
            .ForMember(a => a.Id, (model) => model.PreCondition((context) => context.Id > 0))
            .ForMember( a => a.UpdateDate, (model) => model.PreCondition((context) => context.Id > 0))
            .ForMember( a => a.InsertDate, (model) => model.PreCondition((context) => context.Id == 0));

        AutoMapper.Mapper.CreateMap<Book, BookFormModel>();

var mapper = AutoMapper.Mapper.FindTypeMapFor<IEntity, ListItemModelBase>();
//var mapper = AutoMapper.Mapper.FindTypeMapFor<Book, BookListItemModel>();
mapper.Dump();
mapper.GetPropertyMaps().Dump();

the solution i come up with

var mapper = AutoMapper.Mapper
     .GetAllTypeMaps()
     .Where(a => a.SourceType == typeof(Book) && typeof(ListItemModelBase).IsAssignableFrom(a.DestinationType)                                        && !a.DestinationType.IsAbstract)
     .FirstOrDefault()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM