How to put objects into a dictionary using Dapper in C#?

余生颓废 提交于 2019-12-11 11:44:42

问题


I have a dictionary like the following:

Dictionary<string,SP> dict;

that contains a string and a SP object.

I would like to do the following

dict = conn.Query("SELECT routine_name,created,modified FROM PROCEDURES").toDictionary (
                        row => (string)row.Routine_Name,
                        row => new SP (Name=row.Routine_Name,Created=row.created,Modified=row.modified));

The above code is not working. How can I create a SP object with the above information. I have a constructor that takes these three parameters.


回答1:


  1. Create proper model

    public class SP {
        public string RoutineName { get; set; }
        public DateTime Created { get; set; }
        public DateTime Modified { get; set; }
    }
    
  2. Map your query to model properties, select it to dictionary

    Dictionary<string, SP> dictionary = connection.Query<SP>(@"
        SELECT 
             routine_name AS RoutineName,
             created AS Created,
             modified AS Modified
        FROM PROCEDURES
    ").ToDictionary(m => m.RoutineName, m => m);
    


来源:https://stackoverflow.com/questions/30716092/how-to-put-objects-into-a-dictionary-using-dapper-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!