与此相关的问题,请在这里...
UserManager.AddToRole not working - Foreign Key error
在我的应用程序中,我有一个自定义角色实现
public class Role : IdentityRole<Guid, UserRole>
{
public const string Admininstrator = "Administrator";
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new Guid Id { get; set; }
}
但是使用时会导致此错误
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId". The conflict occurred in database "TestDatabase", table "dbo.AspNetRoles", column 'Id'.
罪魁祸首是……
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new Guid Id { get; set; }
从类中删除它并手动创建唯一的 ID 是有效的...
public Role()
{
Id = Guid.NewGuid();
}
我希望数据库为我执行此操作 - 有什么想法为什么会失败吗?
最佳答案
删除
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new Guid Id { get; set; }
只是
public class Role : IdentityRole<Guid, UserRole>{ }
并使用 Fluent api 添加 DatabaseGenerateOption.Identity
!在自定义 IdentityDbContext
类中添加
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// identity
modelBuilder.Entity<Role>().Property(r => r.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
当您添加迁移时,您将看到 (Id = c.Guid(nullable: false, Identity: true)
)
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.Guid(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
关于c# - 隐藏 Id 属性时自定义 IdentityRole<TKey, TUserRole> 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37136283/