将Dapper IDictionary转换为类?

时间:2019-01-16 17:23:38

标签: c# dictionary dapper

是否可以将IDictionary转换为类?

我的IDictionary看起来像这样

{{DapperRow,   
 Date = '9/25/2014 12:00:00 AM',    
 UserId = '123456',    
 User = 'Timothy'    
}}

我的班级

public class MyClass
{
    public DateTime Date {get; set;}
    public string User {get; set;}
    public int UserId {get; set;}
    public virtual someModel {get; set;}    
}

1 个答案:

答案 0 :(得分:0)

要将您提供的字典转换为您提供的类,您只需向模型类添加一个构造函数即可读取字典值。

public class MyClass
{
    public DateTime Date { get; set; }
    public string User { get; set; }
    public int UserId { get; set; }

    public MyClass(IDictionary<string, object> data)
    {
        Date = DateTime.Parse(data["Date"].ToString());
        User = data["User"].ToString();
        UserId = int.Parse(data["UserId"].ToString());
    }
}

但是Panagiotis是正确的,在这种情况下,您应该利用dapper自动将数据映射到模型中。如果您需要弄清楚它的工作方式或如何进行复杂的映射,他们的readme会非常有用。

相关问题