Skip to content

Instantly share code, notes, and snippets.

@jirkapenzes
Created March 14, 2012 21:43
Show Gist options
  • Save jirkapenzes/2039752 to your computer and use it in GitHub Desktop.
Save jirkapenzes/2039752 to your computer and use it in GitHub Desktop.
Simple data reading from the database in ASP.NET Webforms.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
public class CatRepository
{
private readonly string _connectionString;
public CatRepository()
: base(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString) { }
public CatRepository(string connectionString)
{
_connectionString = connectionString;
}
public List<Cat> GetCats()
{
var connection = new SqlConnection(_connectionString);
var cats = new List<Cat>();
try
{
connection.Open();
var sql = new SqlCommand("Select [Id], [Name] From [Cats] Order by [Name];", connection);
var reader = sql.ExecuteReader();
while (reader.Read())
{
var cat = new Cat()
{
Id = Convert.ToInt16(reader["Id"]),
Name = reader["Name"]
};
cats.Add(cat);
}
}
finally
{
connection.Close();
}
return cats;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment