3

This code in .Net Core 3.1, C# 8:

 await  dB.GetListAsync<OrigineDB>();  

results in this error :

IAsyncEnumerable does not contain a definition for 'GetAwaiter'

The answer provided here : https://stackoverflow.com/a/60148747/4180382 didn't help me much since my method contains a yield and a loop like in the example.

What changes should I make ? I don't want to return a List.

 async IAsyncEnumerable<T> GetListAsync<T>() where T : class, new()
        {
            cn = new SqlConnection(cs);
            cn.Open();
            cmd = new SqlCommand(nameProcStock, cn);
            cmd.CommandType = CommandType.StoredProcedure;

            if (parms != null)
                foreach (KeyValuePair<string, object> kvp in parms)
                    cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);

            dr = await cmd.ExecuteReaderAsync();
            while (dr.Read())
                yield return ConvertToObject<T>();
        }
Ole EH Dufour
  • 2,968
  • 4
  • 23
  • 48

1 Answers1

11

If a method returns an object of the type IAsyncEnumerable<T> you can not await it and in fact you don't have to. You can simply use it in a async foreach loop and use it's content in the body of the loop.

You can consume a IAsyncEnumerable<T> like this:

await foreach (var item in db.GetListAsync<OrigineDB>()) 
{
    // do what ever you want
}
Ackdari
  • 3,222
  • 1
  • 16
  • 33
  • Ok, but I wish to return an IEnumerable object, not having to loop through it... – Ole EH Dufour May 06 '20 at 08:26
  • 1
    @OleEHDufour Why though? Then the return type of you calling function would need to be `Task>` which would not be helpfull in regards to the calling-calling-methode since it only could continue after the whole _list_ was ready to enumerate – Ackdari May 06 '20 at 08:35