字典&LT;字符串,字符串&GT;映射到使用Automapper对象 [英] Dictionary <string,string> map to an object using Automapper
问题描述
下面code仅仅是这个问题。
Below code is just for this question
我有像
public User class
{
public string Name{get;set;}
public string Age{get;set;
}
我有像
Dictionary<string,string> data= new Dictionary<string,string>();
data.Add("Name","Rusi");
data.Add("Age","23");
User user= new User();
现在我要地图用户
使用对象来此字典
Automapper
。 Automapper对象映射,但在我的情况下,有一本字典和对象属性。
Now i want to map User
object to this dictionary
using Automapper
. Automapper maps properties of objects but in my case there a dictionary and object.
所以,请建议我怎么能做到这一点。
So, Please suggest me how can i do this
推荐答案
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));
如果你坚持使用AutoMapper例如,你可以做线沿线的东西:
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));
});
和则:
var data = new Dictionary<string, string>();
data.Add("Name", "Rusi");
data.Add("Age", "23");
var user = Mapper.Map<Dictionary<string, string>, User>(data);
如果您需要的子对象来处理更复杂的对象层次,你必须问自己以下问题:是词典&LT;字符串,字符串&GT;
正确的数据结构使用在这种情况下?
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?
这篇关于字典&LT;字符串,字符串&GT;映射到使用Automapper对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!