Created
June 28, 2011 11:00
-
-
Save einarwh/1050909 to your computer and use it in GitHub Desktop.
DRY data: Final version of Database.cs
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, | |
Func<StoredProcedure, StoredProcedure> configure, | |
Func<IDataRecord, T> map) | |
{ | |
return Execute(spName, configure, | |
cmd => cmd.ExecuteReader(), | |
r => | |
{ | |
var result = new List<T>(); | |
while (r.Read()) | |
{ | |
result.Add(map(r)); | |
} | |
return result; | |
}); | |
} | |
public T ExecuteRow<T>(string spName, | |
Func<StoredProcedure, StoredProcedure> configure, | |
Func<IDataRecord, T> map) | |
{ | |
return ExecuteReader(spName, configure, map).First(); | |
} | |
public T ExecuteScalar<T>(string spName, | |
Func<StoredProcedure, StoredProcedure> configure, | |
Func<object, T> map) | |
{ | |
return Execute(spName, configure, | |
cmd => cmd.ExecuteScalar(), map); | |
} | |
public void ExecuteNonQuery(string spName, | |
Func<StoredProcedure, StoredProcedure> configure) | |
{ | |
Execute(spName, configure, | |
cmd => cmd.ExecuteNonQuery(), | |
o => o); | |
} | |
public TResult Execute<T, TResult>(string spName, | |
Func<StoredProcedure, StoredProcedure> configure, | |
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; | |
configure(new StoredProcedure(cmd, _dpf)); | |
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