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:
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
How would I do this with Dapper?
I assume it is something like:
myDictionary = conn.Query<string, int>(sql, new { }).ToDictionary();
But can't figure out the proper syntax.
I'm not sure if what you're trying to do is possible. If you define a class to map the query to this becomes far more trivial:
Then, you would just do this:
Works also without an additional class:
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:
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'.There's various ways already shown; personally I'd just use the non-generic api:
You can use aliases and strong types.
Aliases are the key points, which match the attributes of KeyValuePair type Key and Value.
It works under strong typing and runs well.
I don't like dynamic type. It brings disaster in certain situations. Moreover, the boxing and unboxing brings performance loss.
Dapper also has an extension method for
ExecuteReader
. So, you could also do this:This approach works without knowing the column names. Moreover, if you don't know the data types, you could change
Dictionary<string,int>
toDictionary<string,object>
andGetInt32(i)
toGetValue(i)
.