C# 自动映射-从字典映射复杂对象<;字符串,对象>;

C# 自动映射-从字典映射复杂对象<;字符串,对象>;,c#,mapping,automapper,automapping,C#,Mapping,Automapper,Automapping,我正在尝试映射以下内容: var values = new Dictionary<string, object>() { ["Address.City"] = "New York", ["FirstName"] = "First Name", ["LastName"] = "Last Name" }; 如果我不更改任何配置,我会将Address设置为null。我尝试过不同的方法。冲突解决程序或只是在MapperConfiguration中编辑我的字典,如下所

我正在尝试映射以下内容:

var values = new Dictionary<string, object>()
{
    ["Address.City"] = "New York",
    ["FirstName"] = "First Name",
    ["LastName"] = "Last Name"
};
如果我不更改任何配置,我会将
Address
设置为null。我尝试过不同的方法。冲突解决程序或只是在
MapperConfiguration
中编辑我的字典,如下所示:

var config = new MapperConfiguration(cfg => {
    const string addressPrefix = "Address.";

    cfg.CreateMap<IDictionary<string, object>, Person>()
    .ForMember(x => x.Address, x => x.MapFrom(c => new Dictionary<string, object>(c.Where(dic => dic.Key.StartsWith(addressPrefix)).ToDictionary(dic => dic.Key.Replace(addressPrefix, string.Empty), dic => dic.Value))));

    cfg.CreateMap<IDictionary<string, object>, Person>()
        .ForMember(dest => dest.Address, opt => opt.ResolveUsing<PersonResolver>());
});
var mapper = config.CreateMapper();
var person = mapper.Map<Person>(values);

您试图从中映射的词典的“名字”和“姓氏”使用的键与唯一配置相同。请尝试从字符串映射到地址。@MrBrown这只是一个输入错误。我已经玩了一段时间了while@LucianBargaoanu我尝试过很多不同的设置,唯一的问题是,关键必须是“地址”。
var config = new MapperConfiguration(cfg => {
    const string addressPrefix = "Address.";

    cfg.CreateMap<IDictionary<string, object>, Person>()
    .ForMember(x => x.Address, x => x.MapFrom(c => new Dictionary<string, object>(c.Where(dic => dic.Key.StartsWith(addressPrefix)).ToDictionary(dic => dic.Key.Replace(addressPrefix, string.Empty), dic => dic.Value))));

    cfg.CreateMap<IDictionary<string, object>, Person>()
        .ForMember(dest => dest.Address, opt => opt.ResolveUsing<PersonResolver>());
});
var mapper = config.CreateMapper();
var person = mapper.Map<Person>(values);
public class PersonResolver : IValueResolver<IDictionary<string, object>, Person, Address>
{
    public Address Resolve(IDictionary<string, object> source, Person destination, Address destMember, ResolutionContext context)
    {
        const string addressPrefix = "Address.";
        var address = new Address();

        if (source.Keys.Any(x => x.StartsWith(addressPrefix, StringComparison.InvariantCulture)))
        {
            var addressItems = source
                .Where(dic => dic.Key.StartsWith(addressPrefix, StringComparison.InvariantCulture))
                .ToDictionary(dic => dic.Key.Replace(addressPrefix, string.Empty, StringComparison.InvariantCulture), dic => dic.Value);

            address = context.Mapper.Map<Address>(addressItems);
        }
        return address;
    }
}