简体   繁体   English

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

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

I have a dictionary like the following: 我有一本类似以下的字典:

Dictionary<string,SP> dict;

that contains a string and a SP object. 包含一个字符串和一个SP对象。

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. 如何使用上述信息创建SP对象。 I have a constructor that takes these three parameters. 我有一个采用这三个参数的构造函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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