无法将Task对象转换为Task SqlDataReader

时间:2014-09-22 11:16:21

标签: c# c#-5.0

我正在创建一个简单的类,但我得到了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();
            }
        }
    }        
}

有什么建议可以解决这个问题吗?

1 个答案:

答案 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);
}