What is the best way to convert DapperRow to Dictionary in Dapper?

.net .net-core c# dapper

Question

IEnumerable with Dapper Row is what my method returns. enter image description here

However, when I attempt to access the data without typecasting it to a specific class, I get a null value. enter image description here

1
1
3/16/2020 2:19:39 PM

Accepted Answer

Let's say you're accessing a SQL database.

    public List<IDictionary<string, object>> DapperSelect(string connectionString, string query, object parameters)
    {
        using (var connection = new SqlConnection(connectionString))
        {
            var result = connection.Query(query, parameters).ToList();

            return result.Select(x => (IDictionary<string, object>)x).ToList();
        }
    }

You shouldn't, in my opinion, transform your output toIDictionary<string, string> Not every item in the dictionary is going to be a string; some of them might be bool, int, double, etc., thus I don't believe it will have the intended result.

However, if you're adamant, you may attempt to do something like

result.Select(x => ((IDictionary<string, object>)x).ToDictionary(ks => ks.Key, vs => vs.ToString())).ToList();

therefore, I do not advise it.

Better than all of that is dapper, which allows you to strongly type any SQL result, thus instead of

connection.Query(query, parameters).ToList();

You would compose

connection.Query<YOURTYPE>(query, parameters).ToList();

3
8/22/2018 6:49:48 PM

Popular Answer

Possibly like this:

var foo = db.Query(
                        "MySp",
                        new { parameters },
                        commandType: CommandType.StoredProcedure)
                    .ToDictionary(
                        row => (int) row.Id,
                        row => (string) row.Name);

with row. denoting the column names, and foo denoting a Dictionary type.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow