1

当我尝试删除我的教师记录时收到以下错误。

DELETE 语句与 REFERENCE 约束“FK_dbo.Department_dbo.Teacher_TeacherID”冲突。冲突发生在数据库“MySchoolBook”、表“dbo.Department”、列“TeacherID”中。该语句已终止。

我的老师模型:

public class Teacher : Person
{
    [Key]
    public Guid TeacherID { get; set; }

    public Guid? AccountID { get; set; }

    public virtual ICollection<Classroom> Classrooms { get; set; }

    public virtual Office Office { get; set; }
}

我的部门型号:

public class Department
{
    [Key]
    public Guid DepartmentID { get; set; }

    [Display(Name = "Administrator")]
    public Guid? TeacherID { get; set; }

    [Required(ErrorMessage = "Name is required.")]
    public String Name { get; set; }

    public virtual Teacher Administrator { get; set; }
    public virtual ICollection<Classroom> Classrooms { get; set; }
}

我的数据库上下文:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<Department>()
                .HasOptional(d => d.Administrator);
        }

编辑:

我想要发生的是当我删除我的教师记录时,我部门的教师 ID 列变为 NULL。

4

1 回答 1

2

我想要发生的是当我删除我的教师记录时,我部门的教师 ID 列变为 NULL。

您必须手动设置TeacherID为。nullEF 不会为您执行此操作:

using (var context = new MyContext())
{
    var teacher = context.Teachers
        .SingleOrDefault(t => t.TeacherID == teacherToDeleteID);

    if (teacher != null)
    {
        var departments = context.Departments
            .Where(d => d.TeacherID == teacherToDeleteID);
        foreach (var department in departments)
            department.TeacherID = null;

        context.Teachers.Remove(teacher);

        context.SaveChanges();
    }
}

编辑

您可以尝试删除循环并仅将部门加载到上下文中。当您删除教师时,自动关系修复可能会将TeacherIDFK设置为null,但我不确定:

using (var context = new MyContext())
{
    var teacher = context.Teachers
        .SingleOrDefault(t => t.TeacherID == teacherToDeleteID);
    if (teacher != null)
    {
        context.Departments.Where(d => d.TeacherID == teacherToDeleteID).Load();
        context.Teachers.Remove(teacher);
        context.SaveChanges();
    }
}
于 2012-09-20T16:05:59.800 回答