DavidGouge
DavidGouge

Reputation: 4623

Get field names from Stored Procedure with 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.

Upvotes: 8

Views: 4499

Answers (2)

Herman Kan
Herman Kan

Reputation: 2292

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

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1063704

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;
    //...
}

Upvotes: 17

Related Questions