Skip to content

Instantly share code, notes, and snippets.

@TerribleDev
Last active August 29, 2015 14:03
Show Gist options
  • Save TerribleDev/f248f559dd89c8dc4b42 to your computer and use it in GitHub Desktop.
Save TerribleDev/f248f559dd89c8dc4b42 to your computer and use it in GitHub Desktop.
DataAccess with Generics
public class DataBase<T> where T : class, IDbConnection, new()
{
//connection string
private string ConnectionString { get; set; }
//connection string in constructor
public DatabaseBase(string connectionstring)
{
//if its null or empty throw error
if (string.IsNullOrWhiteSpace(connectionstring)) throw new ArgumentNullException("connectionstring");
ConnectionString = connectionstring;
}
public TResult QueryDatabase<TResult>(Func<T, TResult> action)
{
using (var x = new T())
{
x.ConnectionString = ConnectionString;
return action(x);
}
}
public void QueryDatabase(Action<T> action)
{
using (var x = new T())
{
x.ConnectionString = ConnectionString;
action(x);
}
}
public async Task<TResult> QueryDatabaseAsync<TResult>(Func<T, Task<TResult>> action)
{
using (var x = new T())
{
x.ConnectionString = ConnectionString;
//Hold here so we dont dispose the database prematurely
return await action(x);
}
}
public async Task QueryDatabaseAsync(Func<T, Task> action)
{
using (var x = new T())
{
x.ConnectionString = ConnectionString;
//Hold here so we dont dispose the database prematurely
await Task.WhenAll(action(x));
}
}
}
@TerribleDev
Copy link
Author

Basic database access with generics...Combined with dapper you can do something like:

QueryDatabase(z=>z.Query("MySproc", new{myparam: "myparam"}, commandType: CommandType.StoredProcedure)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment