【问题标题】:How can I create many to many between IdentityUser and IdentityRole?如何在 IdentityUser 和 IdentityRole 之间创建多对多?
【发布时间】:2016-02-19 14:29:47
【问题描述】:

我正在使用 Microsoft Identity,我需要与 IdentityUserIdentityRole 创建多对多关系。我将属性作为public virtual ICollection<Role> IdentityRoles { get; set; } 添加到IdentityUser 类和public virtual ICollection<User> IdentityUsers { get; set; }IdentityRole,但迁移添加了一个名为RoleUsers 的表。

我想将现有的UserRoles 表用于多对多关系。

我该如何创作?

【问题讨论】:

  • 您确定需要多对多关系吗?还是您只对以下内容感兴趣:1. 与某个用户关联的角色和 2. 与某个角色关联的所有用户?
  • 关系已经是多对多的开箱即用(因此是现有的联结表)。
  • 我确信我需要多对多关系。存在关系,但 IdentityRole Users 属性返回 ICollection 并且 IdentityUser Roles 属性返回 ICollection。我想调用 IdentityUser 中的所有角色和 IdentityRole 中的所有用户。

标签: asp.net-mvc asp.net-identity


【解决方案1】:

用户和角色已经是多对多的了。

using (var context = new MyContext()) 
{     
    var usersAndTheirRoles = context.Users.Include(u => u.Roles).ToList();
    var rolesAndTheirUsers = context.Roles.Include(u => u.Users).ToList();
}

或者你想要做一些不同的事情?

编辑:您可以从角色管理器获取 IdentityRoles:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

foreach (var iur in users.First().Roles)
{
    var identityRole = roleManager.FindById(iur.RoleId);
}

【讨论】:

  • 感谢您的回复。但它不起作用。因为用户中的角色返回 IdentityUserRole 的类型。
  • 是的,设计不正确,但您可以从角色管理器获取信息,或者通过 JOIN 返回角色表。
猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
相关资源
最近更新 更多