如何使用C#中的Dapper将对象放入字典?

时间:2015-06-08 18:06:04

标签: c# sql-server dictionary dapper

我有一个如下字典:

Dictionary<string,SP> dict;

包含字符串和SP对象。

我想做以下

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

以上代码无效。如何使用上述信息创建SP对象。我有一个构造函数,它接受这三个参数。

1 个答案:

答案 0 :(得分:4)

  1. 创建合适的模型

    public class SP {
        public string RoutineName { get; set; }
        public DateTime Created { get; set; }
        public DateTime Modified { get; set; }
    }
    
  2. 将查询映射到模型属性,将其选择为字典

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