首页 > 解决方案 > 具有一对多关系的外键

问题描述

我正在使用 EF Core v5.0.2 和 SQL Server 数据库。

我在两个表中设置了外键。

主键:Student.cs

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

外键:StudentAddress.cs

[Key]
public int Id { get; set; }
public int StudentId { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; }

第二个外键:StudentDetail.cs

[Key]
public int Id { get; set; }
public int StudentId { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; }

DbContext文件:

public class Context : DbContext
{
    public Context(DbContextOptions<Context> options) : base(options)
    {
    }

    public DbSet<Student> Student { get; set; }
    public DbSet<StudentAddress> StudentAddress { get; set; }
    public DbSet<StudentDetail> StudentDetail { get; set; }
}

我收到此错误:

SqlException:INSERT 语句与 FOREIGN KEY 约束“FK_Student Address_Student_StudentId”冲突。冲突发生在数据库“StudData”、表“dbo.Student”、列“Id”中。该语句已终止。

在此处输入图像描述

标签: sql-serverentity-framework-coreforeign-keysprimary-key

解决方案


推荐阅读