SQL stored procedure in .NET Core.
I call SQL stored procedures slightly differently in .NET Core to the way I did in .NET framework as I now pass the connection string through as an argument and I need to remember to add the System.Data.SqlClient NuGet package.
public static List<string> GetBlogSummaries(string connectionString)
{
List<string> headers = new List<string>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("sp__get_required_headers"))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Connection = connection;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
headers.Add(reader[0].ToString());
}
}
reader.Close();
connection.Close();
}
}
return headers;
}
3 Comments
Marcin · 5th April 2019 at 3:34 pm
I like that post. Simple but accurate – contains all whats necessary. It helped me, so.. Thank you!
Farzad · 20th September 2019 at 3:19 pm
I understand in that case , you would only return a list of string , but is there anyway in “>Net core” to map the result froma SQL reader to any type ?
I mean without mapping the individual column manually , something like :
List< theResultList = (New ClassX()).Convert(sqlReader);
Shinigami · 20th September 2019 at 3:55 pm
For that you should probably use EntityFramework