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);

Leave a Reply to Marcin Cancel reply

Your email address will not be published. Required fields are marked *


Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: `POST https://dc.services.visualstudio.com/v2/track` resulted in a `400 Invalid instrumentation key` response: {"itemsReceived":1,"itemsAccepted":0,"errors":[{"index":0,"statusCode":400,"message":"Invalid instrumentation key"}]} in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack trace: #0 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response)) #2 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\P in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113