将主键列添加到Identity User Roles Table

时间:2018-04-16 05:22:22

标签: asp.net-core asp.net-identity identity claims-based-identity role-base-authorization

我正在将IdentityUserRole扩展为另一个名为 WorkspaceId 的主键/外键Id字段。

我收到此错误:“'ApplicationUserRole'在属性'WorkspaceId'上不能有KeyAttribute,因为主键只能在根类型上声明

这是我的ApplicationUserRole类:

public partial class ApplicationUserRole: IdentityUserRole<string>
{

    [Key, ForeignKey("WorkspaceId")]
    public string WorkspaceId { get; set; }

    public virtual Workspace Workspace { get; set; }
}

在DbContext中我正在做:

 modelBuilder.Entity<ApplicationUserRole>(entity =>
            {
                entity.HasKey(k => new { k.RoleId, k.WorkspaceId, k.UserId });
                entity.HasOne(r => r.Workspace).WithMany();
            });

将主键添加到UserRoles表的最佳方法是什么,或者,创建另一个表更好更安全?对于我来说,拥有另一个包含来自IdentityUserRole和WorkspaceId PK / FK的PK / FK的表似乎有点矫枉过正。这意味着我需要维护两个表。

另外,我正在使用.net Core 1.1

更新1

审核并实施调查结果后:herehere

迁移时出现以下错误:

  

'Models.ApplicationUser','Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4 [TUser,TRole,TContext,TKey]'违反了'TUser'类型的约束

这是我的申请用户

 public class ApplicationUser : IdentityUser<string, ApplicationUserClaim, ApplicationUserRole, ApplicationUserLogin>

这是我的用户商店:

 public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, ApplicationDbContext, string, ApplicationUserClaim, ApplicationUserRole, ApplicationUserLogin, ApplicationUserToken, ApplicationRoleClaim>

以下是我在启动时的代码:

services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext, string>()
            .AddDefaultTokenProviders()
            .AddUserStore<ApplicationUserStore>()
            .AddRoleStore<ApplicationRoleStore>();



services.AddScoped<UserStore<ApplicationUser, ApplicationRole, AsherDbContext, string, ApplicationUserClaim, ApplicationUserRole, ApplicationUserLogin, ApplicationUserToken, ApplicationRoleClaim>, ApplicationUserStore>();           
        services.AddScoped<RoleManager<ApplicationRole>>();
        services.AddScoped<SignInManager<ApplicationUser>>();

以下是我的身份模型:

public class ApplicationUserRole : IdentityUserRole<string>
public class ApplicationUserClaim : IdentityUserClaim<string>
public class ApplicationUserLogin : IdentityUserLogin<string>
public class ApplicationRoleClaim : IdentityRoleClaim<string> 
public class ApplicationUserToken : IdentityUserToken<string>
public class ApplicationRole : IdentityRole<string, ApplicationUserRole, ApplicationRoleClaim>

更新2 删除以下行修复了约束违规错误:

.AddEntityFrameworkStores<AsherDbContext, string>()

1 个答案:

答案 0 :(得分:1)

ApplicationUserRole派生自已包含在模型中的IdentityUserRole,因此需要在其上配置密钥,因为它是基类。默认情况下,IdentityDbContext将其密钥配置为{UserId,RoleId}。

这里回答了同样的问题:

Customised IdentityUserRole primary key