1
class TransactionAccess
{
    public static void GetTransactions()
    {
        string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactions = connection.Query<TransactionView>(@"SELECT t.transaction_id,t.account_id,a.account_name, a.type,t.note, t.amount, t.date
                                                               FROM account AS a
                                                               INNER JOIN transaction AS t ON a.account_id = t.account_id");
            transactions.Dump();
        }
    }

    public static void GetTransactionInfo(int id)
    {
        string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactionInfo = connection.Query<TransactionView>(@"SELECT a.account_name, a.type, DATE(t.date), t.amount, t.note, t.transaction_id 
                                                                  FROM transaction AS t 
                                                                  INNER JOIN account AS a ON t.account_id = a.account_id 
                                                                  WHERE t.transaction_id = @id", new { id });
            transactionInfo.Dump();
        }
    }

}

In the above code, I am using connString and connection many times in every function sepeartely. How to reduce and that and use only one connection and connString?

bahanu
  • 11
  • 1

1 Answers1

0

You're already seeing that you have code duplication (that's the commonly used term) inside your class. You are now storing them in each method seperately. How about storing them inside your class?

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 12 '22 at 05:15