UserManager.AddToRole not working - Foreign Key error

爱⌒轻易说出口 提交于 2019-12-06 04:15:52

Replace

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

with fluent api. In custom IdentityDbContext class add

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

After the last update it is clear now - I'm guessing that DatabaseGenerated(DatabaseGeneratedOption.Identity) was added after the tables were created. And actual database does not know that it needs to generate primary key, it expects the clients to provide the key.

If you look in SSMS on ApplicationRoles table (or whatever corresponding table name you have) (right click on the table -> "Design" and look on "Default Value or Binding" on field Id it will be empty. But it should be saying newid():

Migrations not always pick up this change and you end up hanging with errors like you get. The solutions to this is to try adding another EF migration, it should give you something like this:

AlterColumn("dbo.ApplicationRoles", "Id", c => c.Guid(nullable: false, defaultValueSql: "newid()"));

Though this will not always work. Sometimes I had to drop and recreate the table entirely for EF to pick up that I want DB to generate the ID for me.

Or (I think this is a better solution) remove DatabaseGenerated(DatabaseGeneratedOption.Identity) from the attribute above Id field and keep

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

This allows you to define the key yourself before creating the record in the DB. This is better if you are using CQRS architecture. But EF might be funny about removing the attribute and will ask for another migration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!