Search code examples
c#asp.netsql-serverentity-frameworkasp.net-identity

Custom IdentityRole<TKey, TUserRole> fails when hiding the Id property


Question in relation to this, here...

UserManager.AddToRole not working - Foreign Key error

In my application I have a custom Role implementation

public class Role : IdentityRole<Guid, UserRole>
{
    public const string Admininstrator = "Administrator";

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

but when used causes this error

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'.

The culprit is this...

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

removing this from the class and manually creating a unique ID works...

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

I would prefer the database did this for me - any ideas why this is failing?


Solution

  • Remove

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

    just

       public class Role : IdentityRole<Guid, UserRole>{ }
    

    and add DatabaseGeneratedOption.Identity with fluent api! In custom IdentityDbContext class add

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         base.OnModelCreating(modelBuilder);
         // identity
         modelBuilder.Entity<Role>().Property(r => r.Id)
             .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
    

    When you add-migration you will see (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");