Skip to main content
3 of 3
deleted 28 characters in body
Peter Csala
  • 9.9k
  • 1
  • 15
  • 33

One way to reduce repetitive code is through the usage of the template method pattern.

In your template method:

  1. Establish a connection
  2. Execute database operation (this is the customizable step)
  3. Close the connection
private async Task<T> GetAsync<T>(Func<IDbConnection, Task<T>> databaseOperation)
{
    using IDbConnection myConnection = new SnowflakeDbConnection(connectionString: _connectionString);
    myConnection.Open();

    return await databaseOperation(myConnection).ConfigureAwait(false);
}

Then you can rewrite your publicly exposed methods:

public async Task<IEnumerable<T>> GetAllAsync<T>(string selectSqlCommand)
    => await GetAsync(conn => conn.QueryAsync<T>(selectSqlCommand));

public async Task<T> GetSingleOrDefaultById<T>(string sqlCommand, int id)
    => await GetAsync(conn => conn.QuerySingleOrDefaultAsync<T>(sqlCommand, new { id }));
Peter Csala
  • 9.9k
  • 1
  • 15
  • 33