Return async task using LINQ select

.net-core asp.net-core c# entity-framework-core linq

Question

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?

1
3
6/3/2016 7:46:57 AM

Accepted Answer

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.

4
6/3/2016 10:18:23 AM

Popular Answer

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);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow