我正在使用 ASP.NET 身份提供程序和 EF 6 Code First,并且我创建了一个自定义 IdentityUserRole
具有额外列的表 OrganisationId
.自定义表名为 UserRole。
该表当前具有默认主键 UserId
和 RoleId
.
我希望在 IdentityUserRole 表的主键中包含 OrganisationId 列。
我可以在我的数据库中看到 UserRole 表,它是用于用户角色的表(没有 aspnet_userrole 表,当我为用户分配角色时,该表有数据)
我试过这个:
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole").HasKey(x => new { x.UserId, x.RoleId });
但它没有向我显示 OrganisationId 属性。
所以我试过:
modelBuilder.Entity<UserRole>().HasKey(x => new { x.OrganisationId, x.RoleId, x.UserId });
但是当我添加迁移时,Up 和 Down 方法都是空的。
更新(一些代码)
IdentityUserRole 类:
public class UserRole : IdentityUserRole, IOrganisationEntity
{
[Key]
public int OrganisationId { get; set; }
[ForeignKey("OrganisationId")]
public Organisation Organisation { get; set; }
}
DbContext 继承自
IdentityDbContext<User>
和
User
继承自 IdentityRebootUser
更新 2
这是新的 DbContext:
public class MyDbContext : IdentityDbContext<User, Role, string,
IdentityUserLogin, UserRole, IdentityUserClaim>
这是我的新用户类:
public class User : IdentityRebootUser<string, IdentityUserLogin,
Role, IdentityUserClaim>
和角色类:
public class Role : IdentityRole<string, UserRole>
但是,这给了我以下错误:
The type 'MyNamespace.Model.Entities.User' cannot be used as type parameter 'TUser' in the generic type or method 'Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>'. There is no implicit reference conversion from 'MyNamespace.Model.Entities.User' to '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>
我现在可以修改 UserRole 表以添加一个额外的 PK,这正是我想要的。
我现在遇到的问题是,我不能使用默认的 UserStore,因为当我告诉它使用我的自定义“用户”表时,我收到以下错误:
There is no implicit reference conversion from 'MyDB.Model.Entities.User' to 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser'.
所以我实现了我自己的 IUserStore 版本,它会产生异步错误。
如果只有一种方法可以将 UserStore 与我的自定义 User 对象一起使用,我会非常高兴。
最佳答案
您需要自定义所有身份对象以指定不同的 key 。网上有各种教程,但我找到的最好的是来自 www.asp.net .
本质上,您需要为每个对象制作自己的版本,但要从更复杂的版本继承。例如,而不是:
public class ApplicationUser : IdentityUser
{
...
}
你会这样做:
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim>
{
...
}
并重复所有对象,包括 UserStore、UserManager、RoleManager 等。
关于entity-framework - 自定义 IdentityUserRole 主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25055740/