Return async task using LINQ select

12,267

Solution 1

Your can use ToListAsync().

https://msdn.microsoft.com/en-us/library/dn220258(v=vs.113).aspx

var data = await DB.Files
    .Where(file => file.ParentId == parentId)
    .Select
        (
            new 
            { 
                name = file.Name,
                id = file.Id 
            }
        ).ToListAsync();
return data;

Alternatively:

var data = from file in DB.Files
           where file.ParentId == parentId
           select new { name = file.Name, id = file.Id };
return await data.ToListAsync();

Be aware that this will query the data. Also, you may reconsider your method name. When a method is async the naming convention suggest that you append "Async" to your method name.

By convention, you append "Async" to the names of methods that have an Async or async modifier.

Solution 2

ToListAsync() method is not working with enumarable anymore. You can use FromResult method like below :

var data = from file in DB.Files
           where file.ParentId == parentId
           select new { name = file.Name, id = file.Id };
    return await Task.FromResult(data);
Share:
12,267
Roman Kolesnikov
Author by

Roman Kolesnikov

Updated on June 12, 2022

Comments

  • Roman Kolesnikov
    Roman Kolesnikov almost 2 years

    I want to implement function that return list of child items from database asynchronously. So I write a function:

        public async Task<IEnumerable<object>> GetFiles(int parentId)
        {
            var data = from file in DB.Files
                       where file.ParentId == parentId
                       select new { name = file.Name, id = file.Id };
            return data;
        }
    

    However I can see a warning: Async method lasks 'await' operators and will run synchronously. How to rewrite this function into asynchronous?

  • Esko
    Esko over 2 years
    Your answer makes no sense, since as per your linked document about ToListAsync it returns a Task<List> and List-class implements IEnumerable. So yes the return value of ToListAsync is enumerable.