Search code examples
c#.net.net-coredapper

How to convert DapperRow to Dictionary<string,string>


I've a method that returns IEnumerable with Dapper Row. enter image description here

But I'm trying to access the data without typecasting it to a particular class and I'm getting null value. enter image description here


Solution

  • Assuming that you are connecting to an 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();
            }
        }
    

    I don't think that you should be converting your result to IDictionary<string, string> I don't think that has the desired effect you want, not every item in the dictionary is going to be a string, it could be bool, int, double, etc...

    But if you insist, You could try to do something like

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

    but I don't recommend it.

    Better than all of that is that with dapper you can always strongly type the result returned from SQL, so instead of

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

    you would write

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