我正在创建一个简单的类,但我得到了Cannot convert Task object to Task SqlDataReader
。这是我的代码,
public static class SqlHelper
{
enum ExecutionType
{
NonQuery,
Reader,
Scaler
}
public static async Task<int> ExecuteNonQueryAsync(string connectionString, CommandType commandType,
string commandText,
params SqlParameter[] parameters)
{
return (Task<int>)ExecuteAsync(ExecutionType.NonQuery, connectionString, commandType, commandText, parameters);
}
public static async Task<SqlDataReader> ExecuteReaderAsync(string connectionString, CommandType commandType,
string commandText, params SqlParameter[] parameters)
{
return (Task<SqlDataReader>)ExecuteAsync(ExecutionType.Reader, connectionString, commandType, commandText, parameters);
}
public static async Task<object> ExecuteScalarAsync(string connectionString, CommandType commandType, string commandText,
params SqlParameter[] parameters)
{
return ExecuteAsync(ExecutionType.Scaler, connectionString, commandType, commandText, parameters);
}
private static async Task<object> ExecuteAsync(ExecutionType executionType, string connectionString, CommandType commandType, string commandText,
params SqlParameter[] parameters)
{
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(commandText, connection) { CommandType = commandType })
{
command.Parameters.AddRange(parameters);
await connection.OpenAsync();
if (executionType == ExecutionType.Reader)
{
return await command.ExecuteReaderAsync();
}
if (executionType == ExecutionType.NonQuery)
{
return await command.ExecuteNonQueryAsync();
}
return await command.ExecuteScalarAsync();
}
}
}
}
有什么建议可以解决这个问题吗?
答案 0 :(得分:4)
您无法将Task<object>
投射到Task<Foo>
。你想要的是:
return (Foo) await (expression);
即
public static async Task<SqlDataReader> ExecuteReaderAsync(
string connectionString, CommandType commandType,
string commandText, params SqlParameter[] parameters)
{
return (SqlDataReader) await ExecuteAsync(ExecutionType.Reader,
connectionString, commandType, commandText, parameters);
}
(同样适用于int
版本)
注意:您可能还希望在所有ConfigureAwait(false)
表达式上使用await
。例如:
public static async Task<int> ExecuteNonQueryAsync(string connectionString,
CommandType commandType, string commandText, params SqlParameter[] parameters)
{
return (int) await ExecuteAsync(ExecutionType.NonQuery, connectionString,
commandType, commandText, parameters).ConfigureAwait(false);
}