【问题标题】:A key cannot be configured on 'ApplicationUser' because it is a derived type. The key must be configured on the root type 'IdentityUser'无法在“ApplicationUser”上配置密钥,因为它是派生类型。必须在根类型“IdentityUser”上配置密钥
【发布时间】:2021-06-11 18:02:27
【问题描述】:

我正在尝试向 IdentityUser 表添加一个额外的属性。当我想运行迁移时,会出现此错误: 无法在“ApplicationUser”上配置密钥,因为它是派生类型。必须在根类型“IdentityUser”上配置密钥。如果您不打算将“IdentityUser”包含在模型中,请确保它没有被您的上下文中的 DbSet 属性引用、在对 ModelBuilder 的配置调用中引用或从包含在该模型。 我搜索了很多并尝试了它们,但它们都不适合我。

这是应用程序用户类:

public class ApplicationUser:IdentityUser
{
    public bool IsDeleted { get; set; }
}

这是我的上下文:

public class OnlineExamContext : IdentityDbContext<ApplicationUser>
{
    public OnlineExamContext(DbContextOptions<OnlineExamContext> options) : base(options)
    {

    }
    #region Questions
    public DbSet<UserAnswer> userAnswers { get; set; }
    public DbSet<Question> questions { get; set; }
    public DbSet<ChoiceQuestionSelection> choiceQuestionSelections { get; set; }
    public DbSet<QuestionCategory> questionCategories { get; set; }
    public DbSet<TrueFalseQuestion> trueFalseQuestions { get; set; }
    #endregion

    #region users
    public DbSet<UserCourse> userCourses { get; set; }
    #endregion

    #region other entities
    public DbSet<Course> courses { get; set; }
    public DbSet<StudentGrade> studentGrades { get; set; }
    public DbSet<Exam> exams { get; set; }
    public DbSet<SiteSetting> siteSettings { get; set; }
    #endregion

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        var cascadeFKs = modelBuilder.Model.GetEntityTypes()
            .SelectMany(t => t.GetForeignKeys())
            .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);

        foreach (var fk in cascadeFKs)
            fk.DeleteBehavior = DeleteBehavior.Restrict;
                  base.OnModelCreating(modelBuilder);
        
    }

}

这是启动:

services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.Password.RequiredUniqueChars = 0;             
            options.User.AllowedUserNameCharacters =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-";

            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
            
        })

【问题讨论】:

    标签: asp.net-core asp.net-identity


    【解决方案1】:

    我找到了解决方案。我应该将所有 IdentityUsers 更改为 ApplicationUser,甚至是我的模型的导航。像这样:

       public class Question
        {
           [Key]
           public int QuestionId { get; set; }//1
           [ForeignKey("UserId")]
           public virtual ApplicationUser IdentityUser { get; set; }
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-17
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多