Last active
August 29, 2015 14:03
-
-
Save TerribleDev/f248f559dd89c8dc4b42 to your computer and use it in GitHub Desktop.
DataAccess with Generics
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
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basic database access with generics...Combined with dapper you can do something like:
QueryDatabase(z=>z.Query("MySproc", new{myparam: "myparam"}, commandType: CommandType.StoredProcedure)