Using async / await inside .Select lambda
<p>I am using Asp.Net Core Identity and trying to simplify some code that projects a list of users <em>and their roles</em> to a ViewModel.  This code works, but in trying to simplify it I have gone into a crazy spiral of errors and curiosity.</p>

<p><strong>Here is my working code:</strong></p>

<pre><code>        var allUsers = _userManager.Users.OrderBy(x =&gt; x.FirstName);
        var usersViewModel = new List&lt;UsersViewModel&gt;();

        foreach (var user in allUsers)
        {
            var tempVm = new UsersViewModel()
            {
                Id = user.Id,
                UserName = user.UserName,
                FirstName = user.FirstName,
                LastName = user.LastName,
                DisplayName = user.DisplayName,
                Email = user.Email,
                Enabled = user.Enabled,
                Roles = String.Join(", ", await _userManager.GetRolesAsync(user))
            };

            usersViewModel.Add(tempVm);
        }
</code></pre>

<p>In trying to simplify the code, I figured I could do something like this
<strong>(broken code)</strong>:</p>

<pre><code>        var usersViewModel = allUsers.Select(user =&gt; new UsersViewModel
        {
            Id = user.Id,
            UserName = user.UserName,
            FirstName = user.FirstName,
            LastName = user.LastName,
            DisplayName = user.DisplayName,
            Email = user.Email,
            Enabled = user.Enabled,
            Roles = string.Join(", ", await _userManager.GetRolesAsync(user))
        }).ToList();
</code></pre>

<p>This breaks because I'm not using the async keyword in the lambda expression before <em>user</em>.  However, when I do add async before <em>user</em>, I get yet another error that says <em>"Async lambda expressions cannot be converted to expression trees"</em></p>

<p>My guess is that the GetRolesAsync() method is returning a Task and assigning it to Roles instead of the actual results of that task.  What I can't seem to figure out for the life of me is how to make it work.</p>

<p>I have researched and tried many methods over the past day with no luck.  Here are a few that I looked at:</p>

<p><a href="https://stackoverflow.com/questions/12402681/is-it-possible-to-call-an-awaitable-method-in-a-non-async-method">Is it possible to call an awaitable method in a non async method?</a></p>

<p><a href="https://blogs.msdn.microsoft.com/pfxteam/2012/04/12/asyncawait-faq/" rel="noreferrer">https://blogs.msdn.microsoft.com/pfxteam/2012/04/12/asyncawait-faq/</a></p>

<p><a href="https://stackoverflow.com/questions/14938467/calling-async-method-in-ienumerable-select">Calling async method in IEnumerable.Select</a></p>

<p><a href="https://stackoverflow.com/questions/21868087/how-to-await-a-list-of-tasks-asynchronously-using-linq">How to await a list of tasks asynchronously using LINQ?</a></p>

<p><a href="https://stackoverflow.com/questions/27204292/how-to-user-async-await-inside-a-lambda">how to user async/await inside a lambda</a></p>

<p><a href="https://stackoverflow.com/questions/29821263/how-to-use-async-within-a-lambda-which-returns-a-collection">How to use async within a lambda which returns a collection</a></p>

<p>Admittedly, I do not fully understand how async / await work, so that's probably part of the issue.  My foreach code works, but I'd like to be able to understand how to make it work the way I'm trying to.  Since I've spent so much time on it already I figured this would be a good first question.</p>

<p>Thanks!</p>

<p><strong>Edit</strong></p>

<p>I guess I have to explain what I did in each case of the articles I researched in order for this to not be flagged as a duplicate question - and I tried really hard to avoid that :-/.  While the question sounds similar, the results are not.  In the case of the article that was marked as an answer I tried the following code:</p>

<pre><code>    public async Task&lt;ActionResult&gt; Users()
    {
        var allUsers = _userManager.Users.OrderBy(x =&gt; x.FirstName);
        var tasks = allUsers.Select(GetUserViewModelAsync).ToList();
        return View(await Task.WhenAll(tasks));
    }

    public async Task&lt;UsersViewModel&gt; GetUserViewModelAsync(ApplicationUser user)
    {
        return new UsersViewModel
        {
            Id = user.Id,
            UserName = user.UserName,
            FirstName = user.FirstName,
            LastName = user.LastName,
            DisplayName = user.DisplayName,
            Email = user.Email,
            Enabled = user.Enabled,
            Roles = String.Join(", ", await _userManager.GetRolesAsync(user))
        };
    }
</code></pre>

<p>I also tried using AsEnumerable like so:</p>

<pre><code>    var usersViewModel = allUsers.AsEnumerable().Select(async user =&gt; new UsersViewModel
        {
            Id = user.Id,
            UserName = user.UserName,
            FirstName = user.FirstName,
            LastName = user.LastName,
            DisplayName = user.DisplayName,
            Email = user.Email,
            Enabled = user.Enabled,
            Roles = string.Join(", ", await _userManager.GetRolesAsync(user))
        }).ToList();
</code></pre>

<p>Both of these produce the error message: <em>"InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe."</em></p>

<p>At this point it seems like my original ForEach may be the best bet, but I'm still left wondering what would be the right way to do this if I were to do it using the async methods.</p>

<p><strong>Edit 2 - with Answer</strong>
Thanks to Tseng's comments (and some other research) I was able to make things work using the following code:</p>

<pre><code>        var userViewModels = allUsers.Result.Select(async user =&gt; new UsersViewModel
        {
            Id = user.Id,
            UserName = user.UserName,
            FirstName = user.FirstName,
            LastName = user.LastName,
            DisplayName = user.DisplayName,
            Email = user.Email,
            Enabled = user.Enabled,
            Roles = string.Join(", ", await _userManager.GetRolesAsync(user))
        });
        var vms = await Task.WhenAll(userViewModels);
        return View(vms.ToList());
</code></pre>

<p>Although now that I have taken everyone's comments into consideration, I started looking closer at the SQL Profiler just to see how many hits the DB is actually getting - as Matt Johnson mentioned, it's a lot (N+1).  </p>

<p>So while this does answer my question, I am now reconsidering how to run the query and may just drop the roles in the main view and only pull them as each user is selected.  I definitely learned a lot through this question though (and learned more of what I don't know), so thank you everyone. </p>