【问题标题】:ASP .Net Core saving IdentityUser Id as foreign key causes FK violationASP .Net Core 将 IdentityUser Id 保存为外键会导致 FK 违规
【发布时间】:2022-08-23 14:28:07
【问题描述】:

我在 AppUser 类中使用新列扩展了 IdentityUser。

 public class AppUser: IdentityUser
    {
        
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
       
    }

在另一个模型中,我为 AppUser 创建了一个外键和导航属性,如下所示:

 public abstract class TestEntity
    {


        [Key]
        public int Id { get; set; }

        public bool IsActive { get; set; }

        public string UserId { get; set; }

        public virtual AppUser User { get; set;}


    }

然后为了保存,我使用以下代码:

 testEntity.UserId = this.userManager.GetUserId(Request.HttpContext.User);
 await this.context.SaveChangesAsync();

我得到的错误说:

Detail: Key (UserId)=(636511f2-a17b-47ef-9849-acb26a2ddd96) is not present in table \"AppUser\".

但是,此键在 AspNetUsers 表中作为 ID 存在。或许值得一提的是,TestEntity 与 AppUser 位于不同的数据库上下文中。

  • TestEntity 是一个无法实例化的抽象类。你是如何添加迁移的?
  • 抱歉,我在使用 repo 模式时不得不最小化代码,忘记删除抽象关键字..所以抽象关键字不存在..

标签: asp.net-mvc asp.net-core entity-framework-core


【解决方案1】:

报错提示:AppUser表中没有对应行,其中UserId列包含值636511f2-a17b-47ef-9849-acb26a2ddd96

然后,我创建了另一个 Dbcontext,并添加了迁移和更新的数据库, 数据库:

AppUser 表未与您的 IdentityDbContext 中的数据共享数据,因此发生错误,您应该将它们保留在相同的 Dbcontext 中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-14
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多