Last active
April 16, 2024 14:09
-
-
Save joeltennant/7b6f84c51c1f2e44a9847da18fc9f05e to your computer and use it in GitHub Desktop.
Wrapper for Dapper
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 Dapper; | |
using Microsoft.Data.SqlClient; | |
namespace DapperDatabase; | |
public class DapperContext | |
{ | |
//Add Connection string however you want | |
public string? ConnectionString { get; set; } | |
public DapperContext(string connectionString) | |
{ | |
ConnectionString = connectionString; | |
} | |
private SqlConnection CreateConnection() | |
{ | |
return ConnectionString == null ? throw new Exception("Connection string is null") : new SqlConnection(ConnectionString); | |
} | |
private async Task<T> CommandAsync<T>(Func<SqlConnection, Task<T>> func) | |
{ | |
using (var _context = CreateConnection()) | |
{ | |
try | |
{ | |
var result = await func(_context); | |
return result; | |
} | |
catch (Exception ex) | |
{ | |
throw new Exception(ex.Message, ex); | |
} | |
} | |
} | |
private T Command<T>(Func<SqlConnection, T> func) | |
{ | |
using (var _context = CreateConnection()) | |
{ | |
try | |
{ | |
var result = func(_context); | |
return result; | |
} | |
catch (Exception ex) | |
{ | |
throw new Exception(ex.Message, ex); | |
} | |
} | |
} | |
#region ---Querying Methods--- | |
public async Task<IEnumerable<T>> QueryAsync<T>(string sqlQuery, object? param = null) | |
{ | |
return await CommandAsync(async (context) => | |
{ | |
var result = await context.QueryAsync<T>(sqlQuery, param); | |
return result; | |
}); | |
} | |
public IEnumerable<T> Query<T>(string sqlQuery, object? param = null) | |
{ | |
return Command((context) => | |
{ | |
var result = context.Query<T>(sqlQuery, param); | |
return result; | |
}); | |
} | |
public async Task<int> ExecuteAsync(string sqlQuery, object? param = null) | |
{ | |
return await CommandAsync(async (context) => | |
{ | |
var result = await context.ExecuteAsync(sqlQuery, param); | |
return result; | |
}); | |
} | |
public int Execute(string sqlQuery, object? param = null) | |
{ | |
return Command((context) => | |
{ | |
var result = context.Execute(sqlQuery, param); | |
return result; | |
}); | |
} | |
#endregion | |
#region ---Example of Usage--- | |
/* | |
public async Task<User> GetUserById(long UserId) | |
{ | |
var sqlQuery = """ | |
SELECT * FROM Users | |
where UserId = @UserId | |
"""; | |
return await QueryAsync<User>(sqlQuery, new { UserId }); | |
} | |
*/ | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment