I wanted to use Dapper instead of using the normal procedure to map the data. I have gone through the documentation and have some ideas, but I am struggling to get the hang of it.
This is my controller code without using dapper to get data from postgres tables columns and map it to transactionLists:
public IActionResult Index()
{
using var conn = new NpgsqlConnection(connString);
conn.Open();
using var command = new NpgsqlCommand(null, conn);
command.CommandText = "SELECT t.transaction_id, a.account_name, a.type,t.amount,t.date" +
" FROM account AS a " +
" INNER JOIN transaction AS t ON a.account_id = t.account_id";
command.Prepare();
NpgsqlDataReader reader = command.ExecuteReader();
List<Transaction> transactionLists = new List<Transaction>();
if (reader.HasRows)
{
while (reader.Read())
{
transactionLists.Add(new Transaction
{
TransactionId = Convert.ToInt32(reader["transaction_id"]),
AccountName = Convert.ToString(reader["account_name"]),
Type = Convert.ToString(reader["type"]),
Date = Convert.ToDateTime(reader["date"]),
Amount = Convert.ToInt32(reader["amount"]),
});
}
}
ViewBag.accounts = GetAccountLists().OrderByDescending(x => x.AccountName).ToList();
var model = new TransactionViewModel();
model.Transactions = transactionLists;
return View(model);
}
I want to use Dapper like this:
using (NpgsqlConnection connection = new NpgsqlConnection(connString))
{
var transactions = connection.Query("SELECT t.transaction_id,
a.account_name, a.type,t.amount,t.date" +
" FROM account AS a INNER JOIN transaction AS t " +
" ON a.account_id = t.account_id";).AsList();
using (NpgsqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
allTransactionLists.Add(Transaction.FromReader(reader));
}
}
}
}
Can anyone help me how to convert the code into Dapper?