c# - 字典 <string,string> 使用 Automapper 映射到一个对象

标签 c# asp.net-mvc asp.net-mvc-3 dictionary automapper

我有一个类

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();

现在我想使用 AutomapperUser 对象映射到这个 dictionary。 Automapper 映射对象的属性,但在我的例子中有字典和对象。

如何映射?

最佳答案

AutoMapper 在对象的属性之间进行映射,不应该在这种情况下运行。在这种情况下,您需要反射魔法。您可以通过中间序列化作弊:

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,您可以按照以下方式做一些事情:

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);

如果您需要处理带有子对象的更复杂的对象层次结构,您必须问自己以​​下问题:Dictionary<string, string> 是在这种情况下使用正确的数据结构?

关于c# - 字典 <string,string> 使用 Automapper 映射到一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7310533/

相关文章:

c# - 删除单个 RadGrid 列的过滤器

c# - 没有 MVC 的 .Net Core 2 路由

css - 如何在 azure 中包含非标准字体?

asp.net-mvc-3 - 如何在 MVC3 中显示数组

asp.net-mvc-3 - 是否有解决 MVC Controller 操作的 CA1062 的首选方法?

c# - 检查 DateTime 是否为 UTC 格式

c# - 如何创建只读文本框样式

c# - 阻止 EF 检查模型

非矩阵数据类型的 C# 和 MATLAB 互操作性

c# - List<> 无法序列化为 JSON