当远程服务器上的 table 中有现有数据时,在我的 table 中添加外键?

Add foreign key in my table when I have existing data in my table on remote server?

我的学生 table 中已有数据。现在我想在其中添加外键。当我尝试使用现有数据添加外键时,出现错误 "The ALTER TABLE statement conflicted with the FOREIGN KEY constraint"。如果我从 Student table 中删除所有数据,那么它会成功添加外键。现在我想添加外键而不丢失远程服务器上的数据。我该怎么做?我看到了各种答案,但没有找到解决方案。

学生Table(查看最后两个属性)

    public int Id { get; set; }

    [Required]
    [StringLength(30)]
    [RegularExpression(@"^[A-Za-z\s]{1,}[\.]{0,1}[A-Za-z\s]{0,}$", 
    ErrorMessage = "Invalid name. Use letters only")]
    public string Name { get; set; }

    [Required]
    [StringLength(30)]
    [RegularExpression(@"^[A-Za-z\s]{1,}[\.]{0,1}[A-Za-z\s]{0,}$", 
    ErrorMessage = "Invalid name. Use letters only")]
    [Display(Name = "Father Name")]
    public String FatherName { get; set; }


    [Display(Name = "Student Picture")]
    public String ImageURL { get; set; }

    public Class Class { get; set; }

    [Required]
    [Display(Name = "Class Title")]
    public int ClassId { get; set; }

    [ForeignKey("Account")]
    public int AccountId { get; set; }

    public virtual Account Account { get; set; }

    public string Gender { get; set; }

    public string Status { get; set; } = "Active";

    [Required]
    [Range(0, 10000)]
    public int RegistrationFee { get; set; }

    public int InstalmentId { get; set; }

    public virtual Instalment Instalment { get; set; }
    }

这是我的分期付款 table 我想在 Student

中制作 FK
    public int Id { get; set; }

    [Required]
    public int Instalment1 { get; set; }

    [Required]
    public DateTime Date1 { get; set; }

    public int Instalment2 { get; set; }

    public DateTime Date2 { get; set; }

    public int Instalment3 { get; set; }

    public DateTime Date3 { get; set; }

    public int Instalment4 { get; set; }

    public DateTime Date4 { get; set; }
}

我想要一个简单的解决方案,因为将来在很多情况下我会相应地更改数据库。谢谢!

基本上你必须找到哪些记录是冲突的:这是你想要强制执行外键但不满足约束的地方。

然后通过添加缺失数据或更正现有数据来修复错误设置的内容。

然后您就可以将 foreing 键添加到 table。

例如:

如果 PERSON table 中的字段 jobId 是 JOBS table 的外键,并且您在 PERSON table 中有一条记录,其 jobId 为 53 而 53 没有存在于 JOBS table 你将无法 运行 Alter table 添加 foreing 键约束。

首先,您必须将 ID 为 53 的工作添加到 JOBS table,或者如果该工作确实存在但 ID 不同,请更正 PERSON table 中的 jobId。

我希望这能澄清你的疑问。

由于您有现有数据,因此 FK 必须可以为空。所以 FK 必须是 int?.

类型

如果这不适合您的业务逻辑,那么您必须选择一个默认学生并在将更新应用到数据库之前编辑相应的 migration.cs 文件。

恕我直言,可为空的解决方案最适合您的情况:调整您的业务逻辑以适应遗留数据。