自定义IdentityUserRole主键

jao*_*jao 5 entity-framework asp.net-mvc-5 asp.net-identity

我正在使用ASP.NET身份提供程序和EF 6 Code First,我创建了一个IdentityUserRole具有额外列的自定义表OrganisationId.自定义表名为UserRole.

该表当前具有默认主键UserIdRoleId.

我想将OrganisationId列包含在IdentityUserRole表的主键中.

我可以在我的数据库中看到UserRole表,它是用于用户用户的表(没有aspnet_userrole表,当我为用户分配角色时表有数据)

我试过这个:

modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole").HasKey(x => new { x.UserId, x.RoleId }); 
Run Code Online (Sandbox Code Playgroud)

但它没有向我展示OrganisationId属性.

所以我尝试过:

modelBuilder.Entity<UserRole>().HasKey(x => new { x.OrganisationId, x.RoleId, x.UserId });
Run Code Online (Sandbox Code Playgroud)

但是当我添加迁移时,Up和Down方法都是空的.

更新(一些代码)

IdentityUserRole类:

public class UserRole : IdentityUserRole, IOrganisationEntity
{
    [Key]
    public int OrganisationId { get; set; }

    [ForeignKey("OrganisationId")]
    public Organisation Organisation { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

DbContext继承自 IdentityDbContext<User>

User继承自IdentityRebootUser

更新2

这是新的DbContext:

public class MyDbContext : IdentityDbContext<User, Role, string, 
                             IdentityUserLogin, UserRole, IdentityUserClaim>
Run Code Online (Sandbox Code Playgroud)

这是我的新用户类:

public class User : IdentityRebootUser<string, IdentityUserLogin, 
                        Role, IdentityUserClaim>
Run Code Online (Sandbox Code Playgroud)

和角色类:

public class Role : IdentityRole<string, UserRole>
Run Code Online (Sandbox Code Playgroud)

但是,这给了我以下错误:

类型'MyNamespace.Model.Entities.User'不能在泛型类型或方法'Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext <TUser,TRole,TKey,TUserLogin,TUserRole,TUserClaim>'中用作类型参数'TUser' .没有从'MyNamespace.Model.Entities.User'到'Microsoft.AspNet.Identity.EntityFramework.IdentityUser <string,Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin,MyNamespace.Model.Entities.UserRole,Microsoft的隐式引用转换. AspNet.Identity.EntityFramework.IdentityUserClaim>"

更新3

我摆脱了IdentityReboot.我创建了自己的User对象,它具有以下签名:

public class User : IdentityUser<string, IdentityUserLogin, 
                        UserRole, IdentityUserClaim>
Run Code Online (Sandbox Code Playgroud)

我现在可以修改UserRole表来添加额外的PK,这就是我想要的.

我现在的问题是,我不能使用默认的UserStore,因为当我告诉它使用我的自定义'User'表时,我收到以下错误:

没有从"MyDB.Model.Entities.User"到"M​​icrosoft.AspNet.Identity.EntityFramework.IdentityUser"的隐式引用转换.

所以我实现了自己的IUserStore版本,它正在生成异步错误.

如果只有一种方法可以将UserStore与我的自定义User对象一起使用,我会非常高兴.

Dav*_*idG 7

您需要自定义所有标识对象以指定不同的密钥.网上有各种教程,但我发现最好的是www.asp.net.

基本上,您需要为每个对象创建自己的版本,但从更复杂的版本继承.例如,而不是:

public class ApplicationUser : IdentityUser
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

你会这样做:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, 
CustomUserClaim> 
{ 
    ...
}
Run Code Online (Sandbox Code Playgroud)

并重复所有对象,包括UserStore,UserManager,RoleManager等.