来自IConfigurationSection集合的AutoMapper映射

时间:2019-06-06 10:11:46

标签: c# .net-core automapper

我浏览了有关映射集合和嵌套映射以及嵌套集合的映射的文档,但仍然无法解决我的情况。
我有以下json配置文件:

{
  "startupConfig": {
    "noSubscription": {
      "calls": [
        {
          "percentage": 30,
          "techPriority": 1,
          "timePriority": 2
        },
        {
          "percentage": 30,
          "techPriority": 1,
          "timePriority": 2
        }
      ]
    }
  }
}

这是我从文件中读取的代码:

var config = _mapper.Map<FeedConfiguration>(_configuration
    .GetSection("startupConfig").GetChildren()
    .FirstOrDefault(cc => cc.Key == "noSubscription")?.GetChildren());

但是,映射不起作用。这是映射配置的代码:

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

我要映射的类:

namespace FeedService.FeedConfigurations
{
    public class FeedConfiguration
    {
        public ICollection<CallConfiguration> CallsConfig { get; set; }
    }

    public class CallConfiguration
    {
        public int Percentage { get; set; }
        public int TechPriority { get; set; }
        public int TimePriority { get; set; }
    }
}

这是我得到的一个例外:

AutoMapper.AutoMapperConfigurationException: 
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
=============================================================================================================
AutoMapper created this type map for you, but your types cannot be mapped using the current configuration.
IConfigurationSection -> CallConfiguration (Destination member list)
Microsoft.Extensions.Configuration.IConfigurationSection -> FeedService.FeedConfigurations.CallConfiguration (Destination member list)

Unmapped properties:
Percentage
TechPriority
TimePriority

非常感谢您的帮助!
===注意===
我仍然需要这个问题的答案,但是我发布了新的问题,并提供了更好的解释here

1 个答案:

答案 0 :(得分:1)

这里实际上不需要Automepper。只需使用默认的.net核心绑定即可。

重命名这个

 public ICollection<CallConfiguration> CallsConfig { get; set; }

Calls

然后使用类似的东西

 var config  = _configuration.GetSection("startupConfig:noSubscription").Get<FeedConfiguration>();