How to map to a Dictionary object from database results using Dapper Dot Net?

后端 未结 7 2360
庸人自扰
庸人自扰 2020-12-07 22:38

If I have a simple query such as:

string sql = \"SELECT UniqueString, ID  FROM Table\";

and I want to map it to a dictionary object such as

7条回答
  •  囚心锁ツ
    2020-12-07 23:15

    Dapper also has an extension method for ExecuteReader. So, you could also do this:

    var sql = "SELECT UniqueString, ID  FROM Table";
    var rows = new List>();
    using (var reader = cn.ExecuteReader(sql)) {
        while (reader.Read()) {
            var dict = new Dictionary();
            for (var i = 0; i < reader.FieldCount; i++) {
                dict[reader.GetName(i)] = reader.GetInt32(i);
            }
            rows.Add(dict);
        }
    }
    

    This approach works without knowing the column names. Moreover, if you don't know the data types, you could change Dictionary to Dictionary and GetInt32(i) to GetValue(i).

提交回复
热议问题