在 Identity 2.0.0 中,我们在 ApplicationUser 中有 Roles 导航属性,类型为 IdentityUserRoles 并且我们在 IdentityRole 中有相同类型 IdentityUserRoles 的 Users 导航属性
在这里
namespace Microsoft.AspNet.Identity.EntityFramework
{
// Summary:
// EntityType that represents a user belonging to a role
//
// Type parameters:
// TKey:
public class IdentityUserRole<TKey>
{
public IdentityUserRole();
// Summary:
// RoleId for the role
public virtual TKey RoleId { get; set; }
//
// Summary:
// UserId for the user that is in the role
public virtual TKey UserId { get; set; }
}
}
所以,当我遍历 context.Users 时,我只能获得 RoleId
有没有办法在 ApplicationUser 和 ApplicationRole 之间建立标准的多对多映射?
我想做这样的事
foreach (var user in ApplicationDbContextInstance.Users)
{
List<ApplicationRole> UserRoles = user.Roles.ToList();
/*
some logic ...
*/
}
更新:
在解决这个问题后,我找到了适合我的案例的解决方案。 也许它没有那么优雅,但就我而言,我必须使用额外的导航属性扩展 IdentityUserRole
我已将 IdentityUserRole 扩展到 ApplicationUserRole 并在所有解决方案中进行适当的更改。 这是我的新 IdentityUserRole:
public class ApplicationUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
public virtual ICollection<GeoSectorForUser> GeoSectors { get; set; }
}
现在我可以像这样让所有用户担任特定角色:
foreach(ApplicationRole role in db.Roles){
List<ApplicationUser> users = role.Users.Select(s => s.User).ToList();
}
在我的例子中,需要 AplicationUserRole 来存储额外的导航属性,以便该解决方案适合我。 但我仍然想知道如何在 IdentityUser 和 IdentityRole 之间创建干净的多对多关系
最佳答案
IdentityUser.Roles()
为您提供了一组 IdentityUserRole
对象,其中仅包含 RoleId
和 UserId
属性.要为用户获取 Role
对象的集合,您应该使用 RoleManager
类(在我脑海中输入这个,所以可能无法 100% 工作):
var roleManager = new RoleManager();
foreach (var user in ApplicationDbContextInstance.Users)
{
List<IdentityUserRole> UserRoles = user.Roles.ToList();
foreach(var userRole in UserRoles)
{
var role = roleManager.FindbyId(userRole.RoleId);
}
}
关于c# - Identity 2.0.0 中的 ApplicationUser 和 ApplicationRole 导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24823092/