Curious thing:
Here such request fulfills without errors:

IdentityUserRole userRole = user.Roles.Single(r => r.UserId == user.Id); IdentityRole role = roleManager.Roles.Single(r => r.Id == userRole.RoleId); 

But if I combine it into one, then the server crashes:

 IdentityRole role = roleManager.Roles.Single(r => r.Id == user.Roles.Single(ur => ur.UserId == user.Id).RoleId); 

Why it happens? Maybe somehow you can safely fix the second request or there is not much difference? For some reason it seems to me that one request is always more rational to use than two ...

  • (1) What's the mistake? (2) Well, in your second version of the code, an internal query is executed at each iteration of the external query, so it’s not a fact that it really will be an improvement (unless the optimizer understands the way). - VladD
  • @VladD, well, just on the page in the browser, instead of the corresponding view, the text is displayed with the words "internal server error" .. I work with ASP.NET for the first time, I have not learned to debug IIS yet) - guitarhero
  • in ef queries, the lambda expression is assigned to the expression body, which builds a tree of expressions, which will then be used to build a specific sql query, so this lambda expression must be built as simple as it can be disassembled by the sql provider. - Qutrix
  • one
    Usually, if you pass another function as an argument to C # (for example, Fun (FunIn (x));), the compiler will first calculate the inner function, and then the result of the calculations will substitute into the outer function (the so-called "strict calculations"). But .net emulates a lax computational model through delegates and expression , so user.Roles.Single (ur => ur.UserId == user.Id) .RoleId will not be computed before being sent to roleManager.Roles.Single , and the provider will handle it itself too tough - Qutrix
  • one
    "For some reason it seems to me that one request is always more rational to use than two ..." - if we talk about the convenience of support and understanding of the code by other developers, then just the opposite. On some projects, there is even a requirement that all intermediate results have a meaningful name. Of course, it is not necessary to build an absolute, but it is useful to keep in mind - Aleksei

0