我正在尝试为所有用户提供角色名称,但查询悲惨失败并显示错误:
其他信息:无效的列名称“AppRoleId1”。
我的查询是:
var query = this.context.Users
.Include(u => u.Roles)
.ThenInclude(r => r.Role)
.OrderBy(u => u.DisplayName);
我重写IdentityUser
,IdentityUserRole
...并将属性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
的结果为空: