简体   繁体   English

是否可以在ApplicationUser类中将Roles添加为外键?

[英]Is it possible to add Roles as foreign keys in the ApplicationUser class?

I want to show all the users with their roles. 我想向所有用户展示他们的角色。 I am thinking of doing something like this in the ApplicationUser class: 我正在考虑在ApplicationUser类中执行以下操作:

 public string RoleId {get; set;}
 [ForeignKey("RoleId")]
 public UserManager Role {get; set;}

Of course this doesn't return the correct results, but I think there might be a workaround... 当然,这不会返回正确的结果,但是我认为可能有解决方法...

The default identity schema uses a UserRoles table to associate a user's roles to them. 默认身份架构使用UserRoles表将用户角色与其相关联。 If you implemented a custom IdentityDbContext<> you could create the foreign key relationship between your ApplicationUser , UserRole and IdentityRole implementations. 如果实现了自定义IdentityDbContext <> ,则可以在ApplicationUserUserRoleIdentityRole实现之间创建外键关系。

public class ApplicationUser
{
    public List<UserRole> UserRoles { get; set; }
}

public class UserRole
{
    public string UserId { get; set; }

    [ForeignKey(nameof(UserId))]
    public ApplicationUser User { get; set }

    public string RoleId { get; set; }

    [ForeignKey(nameof(RoleId))]
    public IdentityRole Role { get; set }
}

IQueryable<ApplicationUser> GetUsers(IdentityDb db)
{
    return db.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF6 ApplicationUser错误的多个外键 - EF6 Multiple foreign keys for ApplicationUser Error 将声明添加到ApplicationUser的子类 - Add Claims to a sub class of ApplicationUser 模拟 ApplicationUser 并提供角色 - Mock ApplicationUser and provide roles 如何在 EF Core 中的不同项目之间向 ApplicationUser 添加外键? - How to add a foreign key to ApplicationUser between separate project in EF Core? 如何在.Net Identity ApplicationUser模型中添加一个列以指向外部模型? - How to add a column in .Net Identity ApplicationUser model to point to a foreign model? 如何在EF中的同一个class(表)中添加两个外键 - How to add two foreign keys in the same class (table) in EF 在ASP.NET标识中添加与ApplicationUser类的关系(数据库优先) - Add relationships to the ApplicationUser class in ASP.NET Identity (Database First) 无法在webpages_Roles上的SimpleMembership外键错误中添加角色 - Unable to add roles to SimpleMembership foreign key error on webpages_Roles Asp MVC:如何从ApplicationUser获取角色 - Asp MVC: How get roles from ApplicationUser 如何向我的 EF class 添加多个自引用外键? - How do I add multiple self-referencing foreign keys to my EF class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM