Fluent API 不在一对一关系中级联删除

Fluent API not cascading on delete in a one-to-one relationship

我有两个类:

public class Student
{
    public long StudentId { get; set; }
    public StudentDetails details { get; set; }
}

public class StudentDetails
{
    public long StudentDetailsId { get; set; }
    public Student student{ get; set; }
    //other properties
}

一个学生包含一个学生的详细信息。一个学生的详细信息不能没有相应的学生。

使用这些映射:

    public StudentMapping()
    {
        this.ToTable("Student");

        this.HasKey(x => x.StudentId);

        this.HasRequired(x => x.details)
            .WithRequiredDependent(x => x.student)
            .WillCascadeOnDelete(true);
    }

    public StudentDetailsMapping()
    {
        this.ToTable("StudentDetails");

        this.HasKey(x => x.StudentDetailsId);

        this.HasRequired(x => x.student);
    }

但是,当我转到 SQL Management Studio 中的数据库并执行以下操作时:DELETE FROM STUDENTS WHERE StudentId == 1,Student 行被删除,但删除不会级联到 studentdetails 行。出了什么问题?当我删除它的 Student 父对象时,我试图让 StudentDetails 行被删除。

您是否查看了 MSDN 上的 this SO and this 文章?

如我所见,您的模型不是真正的一对一关系,因为您在此处拥有的两个实体不共享 相同 主键。

当您为这样的关系建模时,实际上是在数据库中创建一对多 table 结构:如何防止 StudentDetailsId 不被其他学生使用?我的意思是,您可以使用业务规则来执行它,但严格来说没有规则。

如果你想强制执行一对一的 EF 级联删除,你需要做这样的事情:

public class Student
{
    public long StudentId { get; set; }
    public StudentDetails details { get; set; }
}

    public class StudentDetails
    {
        public long StudentId { get; set; }
        public Student student{ get; set; }
        //other properties
    }

public StudentMapping()
    {
        this.ToTable("Student");

        this.HasKey(x => x.StudentId);

        this.HasRequired(x => x.details)
            .WithRequiredDependent(x => x.student)
            .WillCascadeOnDelete(true);
    }

    public StudentDetailsMapping()
    {
        this.ToTable("StudentDetails");

        this.HasKey(x => x.StudentId);

        this.HasRequired(x => x.student);
    }

希望对您有所帮助:)