c# - 隐藏 Id 属性时自定义 IdentityRole<TKey, TUserRole> 失败

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

但是使用时会导致此错误

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/

相关文章:

c# - 如何在 iOS 上将文本字段居中?

c# - 在 asp.net 中使用 ID 仅更新一列

sql - 错误: "Must declare the scalar variable" for insert statements in multiple database

sql-server - 使用和不使用主键的 SQL Server 插入性能

c# - FluentValidation:仅验证设置了一个属性

c# - 在 XAML 中触发 ContextMenu.IsOpen

c# - Xunit 单元测试不会运行

asp.net - 如何将 Jquery 函数绑定(bind)到 asp.net 按钮并仍然允许验证和回发?

javascript - 浏览器后退按钮asp.net

c# - 按销售额最多的厂商排名记录(数量*价格)