title: EF Core 5.0 - The linq expression could not be translated. either rewrite the query
body: <p>This question has been <a href="https://stackoverflow.com/q/67716627/3845390">asked</a> <a href="https://stackoverflow.com/q/69356206/3845390">before</a> and answered a few times, but not in a generalized way. Rather, the answers are specific to the asker (which makes sense)...but I use this pattern a lot, and I'm sure others do as well, so I'm looking for a more general answer. I know why this is happening, but I'm not sure what to do about it exactly. the offending line below is</p>
  <p><code>RoleId = ur.First(xu =&gt; xu.UserId == x.Id).RoleId,</code></p>
  <p>My understanding is that I have to convert this in some way before the projection, but that's where I'm stuck. Or use <code>Contains()</code> instead of <code>First()</code> (which is an implicit <code>Where()</code> filter), but I'm not sure how to rewrite it so the server will do the query, instead of the client. What is the best way forward?</p>
  <pre class="lang-c# prettyprint-override"><code>         var roles = await _roleManager.Roles.ToListAsync();
           var rolesList = roles.Select(x =&gt; new {x.Id, x.Name}).ToList();
  
           var rid = ur.First(xu =&gt; xu.UserId == 4).RoleId;
           
           var ur = await _context.UserRoles.ToListAsync();
           var appUsers = await _context.Users
               .Select(x =&gt; new AppUserViewModel
               {
                   Id = x.Id,
                   StaffId = x.StaffId,
                   Email = x.Email,
                   UserName = x.UserName,
                   PhoneNumber = x.PhoneNumber,
                   RoleId = ur.First(xu =&gt; xu.UserId == x.Id).RoleId,
                   RoleSelectListItems = rolesList.Select(yy =&gt; new SelectListItem
                   {
                       Value = yy.Id.ToString(),
                       Text = yy.Name
                   }).ToList()
               })
               .ToListAsync();
  
  </code></pre>