且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取分配了角色的用户

更新时间:2023-11-30 10:35:46

默认情况下,UserManager不会加载关系.

UserManager does not load the relations by default.

手动添加是一种好方法,但是如此处-EntityFramework Core尚不支持直接的M:N关系.

The manual inclusion is a good way but as stated here - direct M:N relationships are not yet supported by EntityFramework Core.

所以我有两种查看方式:

So there are two ways I see:

(首选)使用

    userManager.GetRolesAsync(user);

这将返回带有用户角色名称的List<string>.或使用某些EF查询通过联接的IdentityUserRole获取IdentityRole对象.不幸的是,这需要接受事实,即角色将不会直接位于用户实体中.

This will return a List<string> with user's role names. Or use some EF query to get an IdentityRole objects by joined IdentityUserRole. Unfortunatelly, this requires an acceptance with the fact the roles will not be directly in the User entity.

或者您可以实现自定义IdentityUserRole,在此处创建与IdentityRole的关系,然后使用`

OR you can implement custom IdentityUserRole, create a relation to IdentityRole there and then query it with `

Include(user => user.Roles).ThenInclude(role => role.Role)

例如,描述了如何实现自己的身份实体. 此处.但这是复杂的方法,Role对象将嵌套在绑定实体中.

How to implement own Identity entities is described e.g. here. But it's complicated approach and the Role objects will be nested in the binding entities.

但是,您可以在ApplicationUser中声明一个属性:

However, you can declare a property in your ApplicationUser:

[NotMapped]
public List<string> RoleNames {get; set;}

并免费使用它...