当我尝试删除我的教师记录时收到以下错误。
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; }
}
我的DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Department>()
.HasOptional(d => d.Administrator);
}
编辑:
我想要发生的是当我删除我的教师记录时,我的部门的TeacherID列变为NULL。
答案 0 :(得分:2)
我想要发生的是当我删除我的教师记录时,我的 部门的TeacherID列变为NULL。
您必须手动将TeacherID
设置为null
。 EF不会为你做这件事:
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();
}
}
修改强>
您可以尝试删除循环,仅将部门加载到上下文中。当您删除教师时,自动关系修正可能会将TeacherID
FK设置为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();
}
}