隐藏Id属性时,自定义IdentityRole <tkey,tuserrole =“”>失败

时间:2016-05-10 10:47:41

标签: c# asp.net sql-server entity-framework asp.net-identity

与此有关的问题,这里......

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; }
}

但使用时会导致此错误

  

INSERT语句与FOREIGN KEY约束冲突   &#34; FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId&#34 ;.冲突发生了   在数据库&#34; TestDatabase&#34;,table&#34; dbo.AspNetRoles&#34;,column&#39; Id&#39;。

罪魁祸首就是......

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new Guid Id { get; set; }

从课程中删除它并手动创建唯一ID ...

public Role()
{
    Id = Guid.NewGuid();
}

我更希望数据库能为我做到这一点 - 任何想法为什么会失败?

1 个答案:

答案 0 :(得分:2)

删除

itemCount

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public new Guid Id { get; set; }

并使用流畅的api添加 public class Role : IdentityRole<Guid, UserRole>{ } !在自定义DatabaseGeneratedOption.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)