简体   繁体   中英

Convert Dapper IDictionary into a Class?

Is it possible to convert an IDictionary into a class?

My IDictionary looks like this

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

my class

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

To convert the dictionary you provided to the class you provided, you can just add a constructor to the model class to read the dictionary values.

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

But Panagiotis is right, in this situation you should be taking advantage of dapper to automagically map data to your models for you. Their readme is incredibly helpful if you need to figure out how it works or how to do complex mappings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM