Search code examples
c#async-awaitsqlconnectionsqlcommand

How to convert sqlDataReader to Task async


I have the following code-can anyone please tell me if I can make this a async Task

public  MDTO GetIe(MDTO dtoItem)
    {

        string[] Tables = new string[] { "C", "CValue", "SP", "Ar", "P", "CR", "QC", "SR" };
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["tESTp"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("GetItem", connection))
            {
                DataSet Result = new DataSet();
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@ProjectId", SqlDbType.VarChar);
                command.Parameters["@ProjectId"].Value = dtoItem.ProjectId;


                connection.Open();
                Result.EnforceConstraints = false;
                Result.Load(command.ExecuteReader(CommandBehavior.CloseConnection), LoadOption.OverwriteChanges, Tables);
                dtoItem.SR = Result;
            }
        }
        return dtoItem;
    }

Solution

  • Change your command.ExecuteReader to the async version:

    public async Task<MDTO> GetIeAsync(MDTO dtoItem)
    {
        ...
        connection.Open();
        Result.EnforceConstraints = false;
    
        SqlDataReader dataReader = await command.ExecuteReaderAsync(CommandBehavior.CloseConnection);
        Result.Load(dataReader, LoadOption.OverwriteChanges, Tables);
        dtoItem.SR = Result;
        ...
    }