SaveChange() 处的 FK 约束

FK constraint at SaveChange()

学习EF6 code-first。根据外键约定,我会将 StandardId 作为 Student Table 的 FK,而不是丑陋的 Standards_StandardId。尽管我逐字逐句地按照教程进行操作,但在 ctx.SaveChanges() 更新数据库时出现异常。

我认为我的 Entity Framework 的某些约定工作不正常。所以我在 public Standard Part { get; set; } 上尝试了 DataAnnotation [ForeignKey("StandardId")] 来覆盖 FK。但我仍然收到完全相同的错误!

我的 SQL 服务器 "not talking with" 是我的 Entity Framework 还是某些东西损坏了?以下是所有代码和错误消息的详细信息:

实体模型

public class Student {
    public Student() { }
    public int StudentID { get; set; }
    public string StudentName { get; set; }

    //Foreign key for Standard
    public int StandardId { get; set; } <- StandardId, not Standard_StandardId
    public Standard Standard { get; set; } }

public class Standard {
    public Standard() { }
    public int StandardId { get; set; }
    public string StandardName { get; set; } 
    public ICollection<Student> Students { get; set; } }

DbContext 和 DbSet

namespace EF_Code_First_Tutorials {
    public class SchoolContext: DbContext {
        public SchoolContext(): base() { }
        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; } } }

主要

class Program {
    static void Main(string[] args) {
        using (var ctx = new SchoolContext()) {
            Student stud = new Student() { StudentName = "New Student" };  
            ctx.Students.Add(stud);
            ctx.SaveChanges(); } } } <-- ERROR!

在Visual Studio

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

InnerException

{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Students_dbo.Standards_StandardId\". The conflict occurred in database \"EF_Code_First_Tutorials.SchoolContext\", table \"dbo.Standards\", column 'StandardId'.\r\nThe statement has been terminated."}

StudentStandard 之间的关系 不是可选的 ,它是必需的。这意味着,当您保存 Student 时,必须将 StandardId 分配给现有 Standard 记录的 ID。

编辑:

因此,您的程序应包括 Standard 对象的创建:

class Program {
    static void Main(string[] args) {
        using (var ctx = new SchoolContext()) {
            Student stud = new Student() { StudentName = "New Student" };  
            ctx.Students.Add(stud);
            Standard stan = new Standard { StandardId = 524 };
            stud.StantardId = stan.StandardId;
            ctx.Standards.Add(stan);
            ctx.SaveChanges(); } } }

如果你想让关系可选,Student 应该有

public int? StandardId { get; set; }

而不是:

public int StandardId { get; set; }