Created
March 14, 2012 21:43
-
-
Save jirkapenzes/2039752 to your computer and use it in GitHub Desktop.
Simple data reading from the database in ASP.NET Webforms.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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