Dictionary 使用Automapper映射到对象
下面的代码只针对这个问题
我正在上课
public User class { public string Name{get;set;} public string Age{get;set; }
我有一本字典
Dictionary data= new Dictionary(); data.Add("Name","Rusi"); data.Add("Age","23"); User user= new User();
现在我想使用Automapper
将User
对象Automapper
到此dictionary
。 Automapper映射对象的属性,但在我的例子中有一个字典和对象。
所以,请建议我怎么做
AutoMapper在对象的属性之间进行映射,并且不应该在这种情况下运行。 在这种情况下,你需要reflection魔法。 您可以通过中间序列化作弊:
var data = new Dictionary(); data.Add("Name", "Rusi"); data.Add("Age", "23"); var serializer = new JavaScriptSerializer(); var user = serializer.Deserialize(serializer.Serialize(data));
如果你坚持使用AutoMapper,你可以做一些事情:
Mapper .CreateMap, User>() .ConvertUsing(x => { var serializer = new JavaScriptSerializer(); return serializer.Deserialize(serializer.Serialize(x)); });
然后:
var data = new Dictionary(); data.Add("Name", "Rusi"); data.Add("Age", "23"); var user = Mapper.Map, User>(data);
如果需要使用子对象处理更复杂的对象层次结构,则必须问自己以下问题: Dictionary
是否是在这种情况下使用的正确数据结构?
AutoMapper是一个非常灵活的解决方案。 您可以使用自定义映射配置文件实现此目的,例如:
public class UserMappingProfile : Profile { // Props public override string ProfileName { get { return "UserMappingProfile"; } } // Methods public override void Configure() { CreateMap>().ConvertUsing(); base.Configure(); } // Types internal class DictionaryTypeConverter : ITypeConverter> { public User Convert(ResolutionContext context) { var dict = context.SourceValue as Dictionary; if (dict == null) return null; return new User() { Name = dict["Name"], Age = dict["Age"] }; } } }
有了这个,我可以创建一个mapper的自定义实例:
var config = new Configuration(new TypeMapFactory(), MapperRegistry.AllMappers()); config.AddProfile(); config.AssertConfigurationIsValid(); var mapper = new MappingEngine(config);
我可以这样做:
var dict = new Dictionary { { "Name", "Matt" }, { "Age", "27" } }; var user = mapper.Map>(dict);
我刚刚偶然发现了这个问题,我想用当前版本的AutoMapper添加这个答案(即使原来的问题已经很老了):
public class MyConfig { public string Foo { get; set; } public int Bar { get; set; } } var config = new MapperConfiguration(cfg => {}); var mapper = config.CreateMapper(); var source = new Dictionary { ["Foo"] = "Hello", ["Bar"] = 123 }; var obj = mapper.Map(source); obj.Foo == "Hello"; // true
更简单的解决方案。 只需从KeyValuePair映射您的对象。 例:
CreateMap, User>() .ForMember(u => u.Id, src => src.MapFrom(x => x.Key)) .ForMember(u => u.Name, src => src.MapFrom(x => x.Value));