8

我正在使用 Dapper 将 2 列结果集提取到字典中。我注意到当我将鼠标悬停在结果集上时,intellisense 向我显示了一个 .ToDictionary() 但我无法让它工作,因为 dapper 使用动态属性/expandoObject

Dictionary<string, string > rowsFromTableDict = new Dictionary<string, string>();
using (var connection = new SqlConnection(ConnectionString))
{
   connection.Open();
   var results =  connection.Query
                  ("SELECT col1 AS StudentID, col2 AS Studentname 
                    FROM Student order by StudentID");
    if (results != null)
    {
    //how to eliminate below foreach using results.ToDictionary()
    //Note that this is results<dynamic, dynamic>
         foreach (var row in results)
         {
              rowsFromTableDict.Add(row.StudentID, row.StudentName);
         }
         return rowsFromTableDict;
     }
}

谢谢你

4

2 回答 2

14

尝试:

results.ToDictionary(row => (string)row.StudentID, row => (string)row.StudentName);

一旦你有了一个动态对象,你用它做的每一件事以及相应的属性和方法都是动态类型的。您需要定义显式强制转换以将其恢复为非动态类型。

于 2011-10-19T19:01:47.533 回答
-1
if (results != null)
{
    return results.ToDictionary(x => x.StudentID, x => x.StudentName);     
}
于 2011-10-19T17:31:25.427 回答