Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get field names from Stored Procedure with Dapper

Tags:

.net

dapper

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.

like image 908
DavidGouge Avatar asked Oct 01 '13 09:10

DavidGouge


2 Answers

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;
    //...
}
like image 117
Marc Gravell Avatar answered Oct 02 '22 14:10

Marc Gravell


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

like image 30
Herman Kan Avatar answered Oct 02 '22 14:10

Herman Kan