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);
}
}
}
1 Answer 1
Your async/await
usage doesn't look fine because the chain it's incomplete. FindList
should be async
and named FindListAsync
and it should await
the result from QueryAsync
.
There are also a few other things that botter me:
- since
BaseQueryDataStoreAsync
is an abstract class thenQueryAsync
should probably beprotected
and notpublic
- otherwise someone can use it for any query - the
CategoryQueryService
should be injected - the
GetHandler
doesn't look very useful - making the
dbConnectionString
aconst
is a terrible idea - you could/should useappSettings.json
to store it andIConfiguration
orIOptions
to get it - setting
QueryAsync
's default parameters tonull
where they arenull
anyway (source) is pretty pointless - instead just use the overload with a single parameter.
-
\$\begingroup\$
FindListAsync
is public because it is being directly called by the Controller, I will ask a separate question about that. Regarding theCategoryQueryService
, I will read up.GetHandler
is used by other endpoints.dbConnection
is being injected throughIConfiguration
but for this example, I made aconstant
. \$\endgroup\$Coder Absolute– Coder Absolute2018年08月15日 02:15:57 +00:00Commented Aug 15, 2018 at 2:15
Explore related questions
See similar questions with these tags.
QueryAsync<T>
returns anIEnumerable<T>
. \$\endgroup\$