我试图用我自己的UserRoles替换默认的IdentityUserRole类。到目前为止,我所做的事情:
[Table("IdentityUserRole", Schema = "ManagementStudio")]
public class UserRoles : IdentityUserRole<string>
{
[Key]
public string Id { get; set; }
[ForeignKey("Users")]
public override string UserId { get; set; }
public virtual ApplicationUsers Users { get; set; }
[ForeignKey("Roles")]
public override string RoleId { get; set; }
public virtual Roles Roles { get; set; }
}
在我的DbContext类中:
public DbSet<UserRoles> UserRoles{ get; set; }
在我的onModelBuilding
modelBuilder.Entity<UserRoles>()
.ToTable("IdentityUserRole", schema: "ManagementStudio");
这是我尝试登录时遇到的错误:
处理请求时发生未处理的异常。 InvalidOperationException:无法为其创建DbSet 'IdentityUserRole',因为此类型未包含在 上下文模型。 Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityType()
IdentityUserClaim也是如此。
答案 0 :(得分:0)
在DbContext类上继承IdentityDbContext时,应指定新模型UserRole。
喜欢这个。
public class ApplicationDbContext : IdentityDbContext<User, Role, Guid, IdentityUserClaim<Guid>, UserRole , IdentityUserLogin<Guid>, IdentityRoleClaim<Guid>, IdentityUserToken<Guid>>
{
...
}
如您所见,由于要覆盖它,我用UserRole替换了IdentityUserRole。
答案 1 :(得分:0)
如果您查看IdentityUserRole的定义,就会发现它已经具有主键
public class IdentityUserRole<TKey> where TKey : IEquatable<TKey>
{
public IdentityUserRole();
//
// Summary:
// Gets or sets the primary key of the user that is linked to a role.
public virtual TKey UserId { get; set; }
//
// Summary:
// Gets or sets the primary key of the role that is linked to the user.
public virtual TKey RoleId { get; set; }
}
我们必须重写用户角色的实现。现在,如果您看到该代码,就会看到我们可以覆盖它。所以我这样做了:
public class MyDbContext : IdentityDbContext<
User,
Role,
string,
IdentityUserClaim<string>,
UserRole,
IdentityUserLogin<string>,
IdentityRoleClaim<string>,
IdentityUserToken<string>>
//这将覆盖UserRole中的主键:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserRole>(userRole =>
{
userRole.HasKey(pr => new
{
pr.UserId,
pr.RoleId,
pr.ClientId
});
}
}
在覆盖数据库上下文之后,我们可以使用自定义TUserRole, 例如这样的一个:
public class UserRole : IdentityUserRole<string>
{
[Required, StringLength(36)]
public string ClientId { get; set; }
[ForeignKey("ClientId")]
public virtual Client Client { get; set; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}