Hello i am trying to connect with database and return values from a web api controller.I want to do it all the way asynchronous with new task to have better performance if it is possible.here is an example of what i have done.Am i doing it the correct way?Am i using correct the using statements?is the await correct in Open,Close connection and sda.FillAsync ?Thanks!
public async Task<HttpResponseMessage> Get()
{
return await Task.Run(() => GetAllCustomers());
}
private async Task <HttpResponseMessage> GetAllCustomers()
{
DataTable Customers= new DataTable();
using (MySqlConnection con = new MySqlConnection(""))
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customers", con))
{
try
{
if (con.State == ConnectionState.Closed)
{
await con.OpenAsync();
cmd.CommandType = CommandType.Text;
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
await sda.FillAsync(Customers);
}
}
catch (MySqlException ex)
{
ex.Message.ToString();
}
finally
{
await con.CloseAsync();
}
}
return ControllerContext.Request
.CreateResponse(HttpStatusCode.OK, new { Customers });
}
public async Task<HttpResponseMessage> Get()AFAIK, it is recommend to call that MethodGetAsyncthen.catch (MySqlException ex) { ex.Message.ToString();- this is completely useless. Log it at least. But better return an Error Response.