Created
June 20, 2011 18:04
-
-
Save einarwh/1036144 to your computer and use it in GitHub Desktop.
Dry data: Database class
This file contains hidden or 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
| public class Database | |
| { | |
| private readonly string _connStr; | |
| private readonly DbProviderFactory _dpf; | |
| public Database(string connStr): this(connStr, | |
| DbProviderFactories.GetFactory("System.Data.SqlClient")) | |
| {} | |
| public Database(string connStr, DbProviderFactory dpf) | |
| { | |
| _connStr = connStr; | |
| _dpf = dpf; | |
| } | |
| public IEnumerable<T> ExecuteReader<T>(string spName, | |
| DbParameter[] sqlParams, Func<IDataRecord, T> map) | |
| { | |
| return Execute(spName, sqlParams, cmd => cmd.ExecuteReader(), | |
| r => | |
| { | |
| var result = new List<T>(); | |
| while (r.Read()) | |
| { | |
| result.Add(map(r)); | |
| } | |
| return result; | |
| }); | |
| } | |
| public T ExecuteRow<T>(string spName, | |
| DbParameter[] sqlParams, Func<IDataRecord, T> map) | |
| { | |
| return ExecuteReader(spName, sqlParams, map).First(); | |
| } | |
| public T ExecuteScalar<T>(string spName, | |
| DbParameter[] sqlParams, Func<object, T> map) | |
| { | |
| return Execute(spName, sqlParams, | |
| cmd => cmd.ExecuteScalar(), map); | |
| } | |
| public void ExecuteNonQuery(string spName, | |
| DbParameter[] sqlParams) | |
| { | |
| Execute(spName, sqlParams, | |
| cmd => cmd.ExecuteNonQuery(), | |
| o => o); | |
| } | |
| public TResult Execute<T, TResult>(string spName, | |
| DbParameter[] sqlParams, Func<IDbCommand, T> execute, | |
| Func<T, TResult> map) | |
| { | |
| using (var conn = _dpf.CreateConnection()) | |
| using (var cmd = _dpf.CreateCommand()) | |
| { | |
| conn.ConnectionString = _connStr; | |
| conn.Open(); | |
| cmd.Connection = conn; | |
| cmd.CommandType = CommandType.StoredProcedure; | |
| cmd.CommandText = spName; | |
| cmd.Parameters.AddRange(sqlParams); | |
| cmd.CommandType = CommandType.StoredProcedure; | |
| return map(execute(cmd)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment