Get field names from Stored Procedure with Dapper

.net dapper

Question

I am executing a stored procedure with Dapper like this:

var sprocResult = conn.Query("TestSproc", new {clientID = 2}, commandType: CommandType.StoredProcedure).ToList();

I can enumerate the results and list the values. What I need to be able to do though is also enumerate the field names that come back from the sproc. I will not know these field names at design time.

Thanks in advance.

Accepted Answer

When using the dynamic API (the Query(...) instead of Query<T>(...), as per your example), each row also implements IDictionary<string,object>. So basically:

foreach(IDictionary<string,object> row in sprocResult)
{
    var colNames = row.Keys;
    //...
}

Popular Answer

If the query may return no rows, the Query().First().Keys does not work. In this case, you can use ExecuteReader().GetName(i).



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why