I generally end up forgetting how to return results from a SQL stored procedure within .NET so I figured I’d put it here for reference.
public static List<Blog> GetBlogSummaries()
{
List<Blog> blogs = new List<Blog>();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["BlogDatabase"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("sp__get_blog_summaries"))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Connection = connection;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Blog blog = new Blog();
blog.Title = reader[0].ToString();
blog.Description = reader[1].ToString();
blog.DateCreated = (DateTime)reader[2];
blog.Slug = reader[3].ToString();
blogs.Add(blog);
}
}
reader.Close();
connection.Close();
}
}
return blogs;
}
0 Comments