I'm trying to map this:
var values = new Dictionary<string, object>()
{
["Address.City"] = "New York",
["FirstName"] = "First Name",
["LastName"] = "Last Name"
};
into this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string City { get; set; }
}
If I don't change any config, I get Address
as null. I've tried different approaches. A resolver or just editing my dictionary in the MapperConfiguration
like this:
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);
Both cases I successfully get the Address
mapped right, but I lose the First and Last Name. Is there a way to reset the mapper to default for other members?
My resolver:
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;
}
}