Even though @Athanasios Kataras answer works I still went with using the Dapper.contrib extension because it's more clear in my opinion.
I went the route of using Dapper.contrib and creating a Base Repository class which then was used by every other repository.
Primary Keys (IDs) were handled by using data annotations that Dapper provides on the entities ([Key], [ExplicitKey]).
Example of some repository class implementing the Base Repository:
public class ACRepository : BaseRepository<ACEntity>, IACRepository
{
private readonly IDbConnection _dbConnection;
public ACRepository(IDbConnection _dbconn) : base(_dbconn)
{
_dbConnection = _dbconn;
}
// Some other methods that require more complicated queries
}
Base Repository class:
using Dapper.Contrib.Extensions;
public class BaseRepository<T> : IBaseRepository<T> where T : class
{
private readonly IDbConnection _dbConnection;
public BaseRepository(IDbConnection _dbconn)
{
_dbConnection = _dbconn;
}
public async Task Add(T entity)
{
var result = await _dbConnection.InsertAsync(entity);
}
public async Task<bool> Delete(T entity)
{
return await _dbConnection.DeleteAsync(entity);
}
public async Task<bool> Update(T entity)
{
return await _dbConnection.UpdateAsync(entity);
}
public async Task<T> GetById(object id)
{
return await _dbConnection.GetAsync<T>(id);
}
public async Task<IEnumerable<T>> GetAll()
{
return await _dbConnection.GetAllAsync<T>();
}
}
An Entity:
using Dapper.Contrib.Extensions;
[Table("table_name")]
public class SquawkRegisterPMEEntity
{
[ExplicitKey]
public string SomeKey { get; set; }
[Key]
public int SomeOtherKey{ get; set; }
public string SomeProperty { get; set; }
public string SomeProperty1 { get; set; }
}
[Key] is used if the value is generated by the database.
[ExplicitKey] is used when the Id is specified manually.