public async Task <TEntity> InsertThenGet(TEntity entity, int?timeoutSeconds = null) { using (var connection = GetConnection()) { connection.Open(); var tableName = DbConverter <TEntity> .ToTableName(); var columnNames = DbConverter <TEntity> .ToColumnNames(); var parameterNames = DbConverter <TEntity> .ToParameterNames(); var sql = QueryGenerator.GenerateInsertQuery(tableName, columnNames, parameterNames); using (var transaction = connection.BeginTransaction()) { var insertResult = await connection.ExecuteAsync(sql, entity, commandTimeout : timeoutSeconds); if (insertResult == 1) { const string getLastIdQuery = "SELECT LAST_INSERT_ID();"; entity.Id = (await connection.QueryAsync <int>(getLastIdQuery, null, commandTimeout: timeoutSeconds)).First(); } else { throw new Exception($"Inserted result must equal to 1: {insertResult}"); } transaction.Commit(); } connection.Close(); return(entity); } }
public async Task <int> InsertAsync(IEnumerable <TEntity> entities, int?timeoutSeconds = null) { using (var connection = GetConnection()) { connection.Open(); var tableName = DbConverter <TEntity> .ToTableName(); var columnNames = DbConverter <TEntity> .ToColumnNames(); var parameterNames = DbConverter <TEntity> .ToParameterNames(); var sql = QueryGenerator.GenerateInsertQuery(tableName, columnNames, parameterNames); int insertResult; using (var transaction = connection.BeginTransaction()) { insertResult = await connection.ExecuteAsync(sql, entities, commandTimeout : timeoutSeconds); transaction.Commit(); } connection.Close(); return(insertResult); } }