Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return async task using LINQ select

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?

like image 335
Roman Kolesnikov Avatar asked Jun 03 '16 07:06

Roman Kolesnikov


2 Answers

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.

like image 179
smoksnes Avatar answered Oct 23 '22 01:10

smoksnes


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);
like image 6
nzrytmn Avatar answered Oct 23 '22 00:10

nzrytmn