【问题标题】:Customised IdentityUserRole primary key自定义 IdentityUserRole 主键
【发布时间】:2014-07-31 09:46:10
【问题描述】:

我正在使用 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 }); 

但它没有显示 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&lt;User&gt;

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”到“M​​icrosoft.AspNet.Identity.EntityFramework.IdentityUser”的隐式引用转换。

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

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

【问题讨论】:

  • 您的IdentityUserRole 班级是什么样的?另外,你的上下文继承自什么?
  • 我添加了相关代码
  • 好的,所以UserRole 是要使用的对象,尽管我认为它现在使IdentityUserRole 变得多余?您的上下文需要继承自完整的 IdentityDbContext&lt;TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim&gt; 而不是基本的。
  • 确保您的 User 类也继承自正确的位置:IdentityUser&lt;string, IdentityUserLogin, UserRole, IdentityUserClaim&gt;
  • 我通过摆脱 IdentityReboot、更改适当的类并实现我自己的 UserStore 来修复它

标签: entity-framework asp.net-mvc-5 asp.net-identity


【解决方案1】:

您需要自定义所有身份对象以指定不同的键。网上有各种各样的教程,但我发现最好的是来自www.asp.net

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

public class ApplicationUser : IdentityUser
{
    ...
}

你会这样做:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, 
CustomUserClaim> 
{ 
    ...
}

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

【讨论】:

  • @Fraze 那是因为这与 EF Core 无关,它只是 EF6。
猜你喜欢
  • 2022-11-11
  • 2017-02-19
  • 1970-01-01
  • 2022-01-18
  • 2017-11-27
  • 1970-01-01
  • 2018-09-12
  • 2013-05-04
  • 2018-05-31
相关资源
最近更新 更多