【问题标题】:DbInitializer failed, key must be configured on the root typeDbInitializer 失败,必须在根类型上配置密钥
【发布时间】:2018-09-17 00:37:34
【问题描述】:

我最近将我们的 .NET 1.1.4 代码迁移到 .NET 2.0.0 一切似乎都运行良好。现在,我尝试通过以下方式添加新模型/表:

dotnet ef update

我得到以下异常:

DbInitializer 失败!无法在“ApplicationUser”上配置密钥,因为它是派生类型。必须在根类型“IdentityUser”上配置密钥

我有一个扩展 IdentityUser 的 ApplicationUser 和一个扩展 IdentityRole 的 ApplicationRole,这是其他一些教程/stackoverflow 帖子所说的。

我不确定我还缺少什么。

在我的 ApplicationUser 类中,我有:
ICollection<IdentityUserRole<string>>

是否必须是像 ApplicationUserRole 这样的自定义类型? IdentityUserRole 和 IdentityRole 有什么区别?


编辑:
我认为这可能是因为在 OnModelCreating 的 context.cs 文件中,我有:

builder.Entity<ApplicationUser>()
    .ToTable("AspNetUsers")
    .HasKey(x => x.Id);

这里的Id 继承自IdentityUser


EDIT2:
所以我注释掉了那行,那个错误就消失了。它转到下一行,这基本上是相同的,但我的 ApplicationRole 扩展了 IdentityRole。我不太确定这意味着什么。我需要覆盖 id 属性吗?


EDIT3:
好的,所以我将 builder.Entity 中的类型更改为 IdentityUserIdentityRole。为什么在startup.cs中修复它我在调用services.AddIdentity&lt;ApplicationUser, ApplicationRole&gt;时必须使用ApplicationUserApplicationRole

【问题讨论】:

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


    【解决方案1】:

    听起来您在项目的某个地方引用了 IdentityUser。

    Ctrl + F “IdentityUser”整个解决方案然后将对 IdentityUser 的所有引用更改为 ApplicationUser(除了您在 ApplicationUser 类中从它派生的位置)。

    希望对你有帮助

    【讨论】:

    • 我也遇到过这个问题,不过你的回答对了一半。我注意到我只有 IdentityUser 作为我的 ApplicaitonUser 类的派生,所以当我看起来更好时,我注意到问题仍然在 ApplicationUser 类中。如果您从 Microsoft 文档复制粘贴整个代码,您将被默认导航属性卡住,这些属性是 IdentityUserClaim、IdentityUserLogin、IdentityUserToken 和 IdentityUserRole,它们应该转换为 ApplicationUserClaim,...因为您不能在 IdentityXxxxYyyy 类上声明主键两次。
    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    相关资源
    最近更新 更多