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

后端 未结 7 2388
庸人自扰
庸人自扰 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 22:58

    Works also without an additional class:

    var myDictionary = conn.Query>(sql, (s,i) => new KeyValuePair(s,i))
        .ToDictionary(kv => kv.Key, kv => kv.Value);
    

    NOTE: When using Dapper.NET 3.5 version, the Query method that takes the first, second and return types requires you specify more parameters, as the .NET 4.0 and .NET 4.5 versions take advantage of optional arguments.

    In this case, the following code should work:

    string splitOn = "TheNameOfTheValueColumn";
    var myDictionary = conn.Query>(sql, (s,i) => new KeyValuePair(s,i), null, null, false, splitOn, null, null)
            .ToDictionary(kv => kv.Key, kv => kv.Value);
    

    Most of the arguments will revert to a default, but splitOn is required, as it will otherwise default to a value of 'id'.

    For a query that returns two columns, 'ID' and 'Description', splitOn should be set to 'Description'.

提交回复
热议问题