Search code examples
c#dapper

Unable to cast object of type 'DapperRow' to type 'System.String'


I'm using Dapper to access database objects.

So this line

Console.Write(string.Join(System.Environment.NewLine, results));

Gives me

{DapperRow, VALUE_A = 'Y', VALUE_B = 'Y'}

But i'd like to access or print these values like

DapperRow, 
VALUE_A = 'Y'
VALUE_B = 'Y'

But I am getting "System.InvalidCastException: Unable to cast object of type 'DapperRow' to type 'System.String'" with the following code. Where i am trying to use foreach to loop through this list.

using (var conn = new OracleConnection("Password=xxxxx;Persist Security Info=True;User ID=xxxxx;Data Source=xxxxx"))
{
// dapper adds an extension method to the connection for querying
string sql = "SELECT X, Y FROM Z WHERE ABC = 123";
var results = conn.Query(sql).ToList();
Console.Write(string.Join(System.Environment.NewLine, results));

    foreach (string value in results)
    {
    Console.WriteLine("> {0}",value);
    }
}

Solution

  • Actually this gives me the result i want..

    using (var conn = new OracleConnection("Password=xxxxx;Persist Security Info=True;User ID=xxxxxxx;Data Source=xxxxxx"))
    {
    string sql = "SELECT X, Y FROM Z WHERE ABC = 123";
    var orderDetail = conn.Query(sql).FirstOrDefault();
    
        foreach (var pair in orderDetail)
        {
            Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
        }
    }
    
    Output: 
    VALUE_A = 'Y'
    VALUE_B = 'Y'
    

    Then with something like this i can get a value of 'Y' returned.

    if (pair.Key == "VALUE_B")
    {
    Console.WriteLine("Val {0}", pair.Value);
    }