且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

来自IConfigurationSection集合的AutoMapper映射与复杂映射

更新时间:2021-12-07 22:13:58

您的个人资料必须看起来像这样

Your profile must look like this

namespace FeedService.FeedConfigurations
{
    public class FeedConfigurationMappingProfile : Profile
    {
        public FeedConfigurationMappingProfile()
        {
            CreateMap<IConfigurationSection, FeedConfiguration>()
                .ForMember(fc => fc.Calls,
                    mo => mo.MapFrom(fc => fc.Get<FeedConfiguration>().Calls));

            CreateMap<IConfigurationSection, CallConfiguration>()
                .ForMember(cc => cc.Percentage,
                    mo => mo.MapFrom(css => css.GetChildren().FirstOrDefault(cs => cs.Key == "percentage").Value))
                .ForMember(cc => cc.TechPriority,
                    mo => mo.MapFrom(css => css.GetChildren().FirstOrDefault(cs => cs.Key == "techPriority").Value))
                .ForMember(cc => cc.TimePriority,
                    mo => mo.MapFrom(css => css.GetChildren().FirstOrDefault(cs => cs.Key == "timePriority").Value));
        }

    }
}

然后使用映射器

_mapper.Map<FeedConfiguration>(_configuration.GetSection("startupConfig:noSubscription"));

EDIT(附加选项)

EDIT(additional option)

CreateMap<IConfigurationSection, FeedConfiguration>()
                .ForMember(fc => fc.Calls,
                    mo => mo.MapFrom(fc => fc.GetChildren().FirstOrDefault(fd=>fd.Key == "calls").GetChildren()));