How to use a stored procedure to retrieve a returned specific column in Dapper?

To use a stored procedure and retrieve a returned specific column, you have 3 choices:

  1. By mapping returned data to an anonymous type and select your column:
language-csharp
using (var connection = new SqlConnection("connectionString")) { var result = connection.Query("MyStoredProcedure", commandType: CommandType.StoredProcedure).ToList(); var specificColumnList = result.Select(x => (string)x.MyColumn).ToList();

}

  1. By mapping returned data to a strongly typed object and select your column:
language-csharp
public class MyStoredProcedureResult { public string MyColumn { get; set; } // Add other properties as needed, to match all columns returned by the stored procedure

}

using (var connection = new SqlConnection("connectionString")) { var result = connection.Query<MyStoredProcedureResult>("MyStoredProcedure", commandType: CommandType.StoredProcedure).ToList();

var specificColumnList = result.Select(x =&gt; x.MyColumn).ToList();

}

  1. By using QueryMultiple (Multi-Mapping) and read returned data with an anonymous type or strongly typed object:
language-csharp
using (var connection = new SqlConnection("connectionString")) { using (var multi = connection.QueryMultiple("MyStoredProcedure", commandType: CommandType.StoredProcedure)) { var firstResultSet = multi.Read().ToList(); var specificColumnFromFirstResultSet = firstResultSet.Select(x => (string)x.MyColumn).ToList(); } }

NOTE: All columns are returned from the stored procedure, not only the desired selected column.

Sponsored by Dapper Plus
This field is required
A text with a minimum of 10 characters is required
Answer generated by AI may produce inaccurate information about code, people, facts, and more.