【发布时间】:2014-07-31 09:46:10
【问题描述】:
我正在使用 ASP.NET 身份提供程序和 EF 6 Code First,我创建了一个自定义 IdentityUserRole 表,其中有一个额外的列 OrganisationId。自定义表名为 UserRole。
表当前默认主键UserId和RoleId。
我希望将 OrganisationId 列包含在 IdentityUserRole 表的主键中。
我可以在我的数据库中看到 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>
还有 Role 类:
public class Role : IdentityRole<string, UserRole>
但是,这给了我以下错误:
类型“MyNamespace.Model.Entities.User”不能用作类型 泛型类型或方法中的参数“TUser” 'Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext
'。 没有隐式引用转换 'MyNamespace.Model.Entities.User' 到 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser '
更新 3
我摆脱了 IdentityReboot。我创建了自己的用户对象,它具有以下签名:
public class User : IdentityUser<string, IdentityUserLogin,
UserRole, IdentityUserClaim>
我现在可以修改 UserRole 表以添加额外的 PK,这正是我想要的。
我现在遇到的问题是,我不能使用默认的 UserStore,因为当我告诉它使用我的自定义“用户”表时,我收到以下错误:
没有从“MyDB.Model.Entities.User”到“Microsoft.AspNet.Identity.EntityFramework.IdentityUser”的隐式引用转换。
所以我实现了我自己的 IUserStore 版本,它会生成异步错误。
如果有一种方法可以将 UserStore 与我的自定义 User 对象一起使用,我会非常高兴。
【问题讨论】:
-
您的
IdentityUserRole班级是什么样的?另外,你的上下文继承自什么? -
我添加了相关代码
-
好的,所以
UserRole是要使用的对象,尽管我认为它现在使IdentityUserRole变得多余?您的上下文需要继承自完整的IdentityDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>而不是基本的。 -
确保您的 User 类也继承自正确的位置:
IdentityUser<string, IdentityUserLogin, UserRole, IdentityUserClaim> -
我通过摆脱 IdentityReboot、更改适当的类并实现我自己的 UserStore 来修复它
标签: entity-framework asp.net-mvc-5 asp.net-identity