Dictionary <String,String> Map to an Object Using Automapper

Dictionary string,string map to an object using Automapper

AutoMapper maps between properties of objects and is not supposed to operate in such scenarios. In this case you need Reflection magic. You could cheat by an intermediate serialization:

var data = new Dictionary<string, string>();
data.Add("Name", "Rusi");
data.Add("Age", "23");
var serializer = new JavaScriptSerializer();
var user = serializer.Deserialize<User>(serializer.Serialize(data));

And if you insist on using AutoMapper you could for example do something along the lines of:

Mapper
.CreateMap<Dictionary<string, string>, User>()
.ConvertUsing(x =>
{
var serializer = new JavaScriptSerializer();
return serializer.Deserialize<User>(serializer.Serialize(x));
});

and then:

var data = new Dictionary<string, string>();
data.Add("Name", "Rusi");
data.Add("Age", "23");
var user = Mapper.Map<Dictionary<string, string>, User>(data);

If you need to handle more complex object hierarchies with sub-objects you must ask yourself the following question: Is Dictionary<string, string> the correct data structure to use in this case?

Automapper map Dictionarystring, string and Liststring properties to view model

Here's what I assume

// Just demo class
public class StripeProductSeed
{
public string PictureUrl { get; set; }
public int EventLimit { get; set; }
public bool HelpCenterAccess { get; set; }
public bool EmailSupport { get; set; }
public bool PriorityEmailSupport { get; set; }
public bool PhoneSupport { get; set; }
public bool BestValue { get; set; }

public List<string> ExtractImages() => new() { PictureUrl };

public Dictionary<string, string> ExtractMetaData() => new()
{
{nameof(EventLimit), EventLimit.ToString()},
{nameof(HelpCenterAccess), HelpCenterAccess.ToString()},
{nameof(EmailSupport), EmailSupport.ToString()},
{nameof(PriorityEmailSupport), PriorityEmailSupport.ToString()},
{nameof(PhoneSupport), PhoneSupport.ToString()},
{nameof(BestValue), BestValue.ToString()}
};
}

The map should be:

public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<StripeProductSeed, PlanDetail>()
.ForMember(dst => dst.Images, x => x.MapFrom(src => src.ExtractImages()))
.ForMember(dst => dst.Metadata, x => x.MapFrom(src => src.ExtractMetaData()));
}
}

How to Map from Dictionary to Object using Automapper?

For future reference: To fix the problem either follow @Oliver code above or this code as @ASpirin pointed out.

    cfg.CreateMap<Dictionary<Action, bool>, WebAction>()
.ForMember(dest => dest.IsFbClicked,
opt => opt.MapFrom(s => s.ContainsKey(Action.IsFbClicked)?s[Action.IsFbClicked]:fals‌​e))
.ForMember(dest => dest.IsTwitterClicked,
opt => opt.MapFrom(s => s.ContainsKey(Action.IsTwitterClicked)?s[Action.IsTwitterClicked]:fals‌​e))

});


Related Topics



Leave a reply



Submit