Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 777
ThejaSingireddy Avatar asked Aug 22 '18 17:08

ThejaSingireddy


2 Answers

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();

like image 187
Tarek Avatar answered Nov 14 '22 23:11

Tarek


Something like this:

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

With row. being the names of the columns and foo being of type Dictionary .

like image 32
RandomUs1r Avatar answered Nov 14 '22 22:11

RandomUs1r