The following C# code is written to fetch the Categories data from SQL Server Database using Asynchronous Task for HttpGet
. The Dapper library is used as ORM.
I need help to identify whether the Async Task implementation is correct or any better way to implement.
CategoriesController.cs
public class CategoriesController : Controller
{
[HttpGet]
public async Task<IActionResult> FindList(CategorySearchModel searchModel)
{
var results = await new CategoryQueryService().FindList();
return GetHandler(results);
}
IActionResult GetHandler(object results)
{
return new OkObjectResult(new { results });
}
}
CategoryQueryService.cs
public class CategoryQueryService : BaseQueryDataStoreAsync<CategoryQueryModel>
{
public override Task<IEnumerable<CategoryQueryModel>> FindList()
{
const string dbConnectionString = "-- db connection string here --";
const string sql = "SELECT CategoryId, CategoryName FROM Category ORDER BY CategoryName ASC";
return QueryAsync(dbConnectionString, sql);
}
}
CategoryQueryModel.cs
public class CategoryQueryModel {
public int CategoryId { get; set; }
public int CategoryName { get; set; }
}
BaseQueryDataStoreAsync.cs
using Dapper;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading.Tasks;
public abstract class BaseQueryDataStoreAsync<T> where T : class
{
public abstract Task<IEnumerable<T>> FindList();
public async Task<IEnumerable<T>> QueryAsync(string dbConnectionString, string sql)
{
using (var connection = new SqlConnection(dbConnectionString))
{
return await connection.QueryAsync<T>(sql, conditions: null, transaction: null, commandTimeout: null, commandType: null);
}
}
}
QueryAsync<T>
returns anIEnumerable<T>
. \$\endgroup\$