sql-server - 具有一对多关系的外键
问题描述
我正在使用 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”中。该语句已终止。
解决方案
推荐阅读
- node.js - Knex.js PostgreSQL 列引用“id”不明确
- javascript - Javascript 等待带有 async/await 的函数完成
- angular - 角度更新而不是替换对象
- java - Jackson 深度依赖序列化
- java - 我如何在 android 中使用自定义适配器按字母顺序执行搜索
- flutter - 在 Flutter 中导航到 ListView 后,图像未在 Hero 中显示
- opencv - canny 边缘检测算法是否适用于梯度变化较小的图像?
- java - 在 Maven 中指定 Apache Tomcat“lib”文件夹
- android - java.lang.IllegalStateException:应为 BEGIN_OBJECT 但为 BEGIN_ARRAY Kotlin
- java - 如何用最少的代码比较两个字符串列表的java集合?