In order to not rewrite basic CRUD for each entity I want to implement a base entity class with the base CRUD operations that can be implemented by any other entity.
The problem is I'm using Dapper for mapping with Dapper.Contrib and my database tables primary keys are never named Id - I can't use the Dapper mapper then.
I can't figure out a way to have a base class for a simple CRUD for each entity.
There is a very nice implementation without contrib of the generic repository pattern here: https://itnext.io/generic-repository-pattern-using-dapper-bd48d9cd7ead
Effectively you create the insert like this:
public async Task InsertAsync(T t)
{
var insertQuery = GenerateInsertQuery();
using (var connection = CreateConnection())
{
await connection.ExecuteAsync(insertQuery, t);
}
}
private string GenerateInsertQuery()
{
var insertQuery = new StringBuilder($"INSERT INTO {_tableName} ");
insertQuery.Append("(");
var properties = GenerateListOfProperties(GetProperties);
properties.ForEach(prop => { insertQuery.Append($"[{prop}],"); });
insertQuery
.Remove(insertQuery.Length - 1, 1)
.Append(") VALUES (");
properties.ForEach(prop => { insertQuery.Append($"@{prop},"); });
insertQuery
.Remove(insertQuery.Length - 1, 1)
.Append(")");
return insertQuery.ToString();
}