2

I am trying to get all users with role names, but query miserable fails with error:

Additional information: Invalid column name 'AppRoleId1'.

My query is:

var query = this.context.Users
                .Include(u => u.Roles)
                .ThenInclude(r => r.Role)
                .OrderBy(u => u.DisplayName);

I override IdentityUser, IdentityUserRole ... and add property Role to AppUserRole class so ThenInclude could work:

[Table("UserRoles")]
public partial class AppUserRole : IdentityUserRole<int>
{
    public AppUser User { get; set; }
    public AppRole Role { get; set; }

    public AppUserRole() { }

    public AppUserRole(AppUser user, AppRole role)
    {
        this.RoleId = role.Id;
        this.UserId = user.Id;
    }
}

Entity Framework generates this SQL:

SELECT [u3].[RoleId], [u3].[UserId], [u3].[AppRoleId1], [u3].[AppUserId], [r].[Id], [r].[ConcurrencyStamp], [r].[Name], [r].[NormalizedName]
FROM [UserRoles] AS [u3]
INNER JOIN (
    SELECT DISTINCT [u].[DisplayName], [u].[Id]
    FROM [Users] AS [u]
) AS [u4] ON [u3].[UserId] = [u4].[Id]
LEFT JOIN [Roles] AS [r] ON [u3].[AppRoleId1] = [r].[Id]
ORDER BY [u4].[DisplayName], [u4].[Id]

which is odd (where on earth did it get AppRoleId1 column?).

I think this should work, also based on this thread, but it is not. Why? Is there a bug in Entity Framework?

Edited:

I did migrations (dotnet ef migrations add ...) and error is gone, but result is null for query.Single().Roles[0].Role:enter image description here

Community
  • 1
  • 1
Makla
  • 9,899
  • 16
  • 72
  • 142
  • Did you ever get to the bottom of this? I have a similar issue at https://stackoverflow.com/questions/51805713/entity-framework-core-incorrectly-querying-relationships – Evonet Aug 12 '18 at 04:51
  • 1
    Hi @Evonet. I don't know. So much has change in my code. Currently I am using Openiddict, my `AppRole`, `AppUserRole` ... inherits from `IdentityRole`, `IdentityUserRole` ... The whole process of login is entirely different with [Openiddict](https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Controllers/AuthorizationController.cs) (many separate queries) so I don't need to get users with roles with one query anymore. – Makla Aug 13 '18 at 05:26

0 Answers0