实体框架(ASP.NET核心1)列出具有角色名称的所有用户

时间:2017-02-22 10:03:10

标签: entity-framework asp.net-core

我正在尝试为所有用户提供角色名称,但查询悲惨失败并显示错误:

  

其他信息:无效的列名称“AppRoleId1”。

我的查询是:

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

我重写IdentityUserIdentityUserRole ...并将属性Role添加到AppUserRole类,以便ThenInclude可以工作:

[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;
    }
}

实体框架生成此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]

这是奇怪的(在地球上它得到AppRoleId1列?)。

我认为这应该有效,也基于this线程,但事实并非如此。为什么?实体框架中是否存在错误?

编辑:

我进行了迁移(dotnet ef migrations add ...)并且错误消失了,但query.Single().Roles[0].Role的结果为空:enter image description here

0 个答案:

没有答案