I'm using Dapper in my project. My project consist 3 layers. API, Business and Repository layers.
I want user async query of dapper.
Below is code in each layer.
At Repository layer
public Task<int> ChangeStatus(DriverStatus driverStatus)
{
using (IDbConnection connection = DapperConnection)
{
var updateQuery = @"UPDATE [dbo].[DriverLocation] Set [Latitude]=@Latitude, [Longitude]=@Longitude, [IsOnline]=@IsOnline Where [DriverId]=@DriverId";
return connection.ExecuteAsync(updateQuery, new
{
Latitude = driverStatus.Latitude,
Longitude = driverStatus.Longitude,
IsOnline = driverStatus.IsOnline,
DriverId = driverStatus.DriverId
});
}
}
Now My Business layer method calls above repository method .
public Task<int> ChangeStatus(DriverStatus driverStatus)
{
try
{
//Some Code here.
return driverRepository.ChangeStatus(driverStatus);
}
catch (Exception ex)
{
Logger.Error(ex);
return Task.FromResult<int>(0);
}
}
Now API method call the business layer method.
public async Task<IHttpActionResult> ChangeStatus(DriverStatus driverStatus)
{
ApiResponse apiResponse = new ApiResponse();
var isUpdated = await driverBl.ChangeStatus(driverStatus);
if(isUpdated > 0)
{
apiResponse.Message = "Driver status changed successfully.";
return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, apiResponse));
}
else
{
apiResponse.Message = "Driver status could not be changed.";
return ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, apiResponse));
}
}
As I have used await keyword only inside my API method, so It might be possible that my connection object got disposed before returning result, So it throw me below error.
BeginExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
How can use async method of dapper using using
statement?