【发布时间】:2019-06-06 10:11:46
【问题描述】:
我浏览了有关映射集合和嵌套映射以及嵌套集合映射的文档,但仍然无法处理我的情况。
我有以下 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。
【问题讨论】:
-
“不起作用”怎么办?
-
好点,我更新了我的问题,谢谢
-
为什么不使用默认的.net核心配置绑定?
-
@RomanMarusyk 你是对的,我可以在这里轻松使用它。
标签: c# .net-core automapper