情景是:
我有两张桌子。
他们之间存在一对多的关系。
我试图通过删除EnrollmentSubject和添加新子项中的子项来更新注册,我在context.SaveChanges()时遇到错误:在Entityframework 6.0中
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted
这是我的代码:
public string UpdateEnrollment(EnrollmentDTO enrollDetail)
{
try
{
List<EnrollmentSubjectDTO> subjectsDTO = new List<EnrollmentSubjectDTO>();
using (SMSEntities em = new SMSEntities())
{
Enrollment enroll = (from aa in em.Enrollments.Include("EnrollmentSubjects")
where aa.EnrollmentId == enrollDetail.EnrollmentId
select aa).FirstOrDefault<Enrollment>();
enroll.Status = enrollDetail.Status;
enroll.RegNo = enrollDetail.RegNo;
enroll.PkgId = enrollDetail.PkgId;
enroll.SectionId = enrollDetail.SectionId;
enroll.AdmittedDate = enrollDetail.AdmittedDate;
enroll.StudentId = enrollDetail.StudentId;
subjectsDTO = enrollDetail.EnrollmentSubjects.ToList<EnrollmentSubjectDTO>();
List<EnrollmentSubject> enrolllist = enroll.EnrollmentSubjects.ToList<EnrollmentSubject>();
if (enroll.ClassId != enrollDetail.ClassId && enroll.GroupId != enrollDetail.GroupId)
{
foreach (EnrollmentSubject obj in enrolllist)
{
enroll.EnrollmentSubjects.Remove(obj);
}
}
enroll.ClassId = enrollDetail.ClassId;
enroll.GroupId = enrollDetail.GroupId;
for (int i = 0; i < subjectsDTO.Count; i++)
{
if (subjectsDTO[i].EnrollmentSubjectId == 0)
{
enroll.EnrollmentSubjects.Add(new EnrollmentSubject()
{
Status = subjectsDTO[i].Status,
SubjectId = subjectsDTO[i].SubjectId
});
}
else
{
enrolllist[i].SubjectId = subjectsDTO[i].SubjectId;
enrolllist[i].Status = subjectsDTO[i].Status;
}
}
// em.Enrollments.Add(enroll);
em.SaveChanges();
return "Enrollment Updated";
}
}
catch(Exception ex)
{
return ex.Message.ToString();
}
}
请指导我
答案 0 :(得分:0)
我的问题解决了...... 我从父母那里删除了它,孩子们的记录变成了父母= null的孤儿,在必要的关系中,如果没有父母,孩子就不能存在。但我是他们在上下文中所以我也从上下文中删除了它们。
if (enroll.ClassId != enrollDetail.ClassId && enroll.GroupId != enrollDetail.GroupId)
{
foreach (EnrollmentSubject obj in enrolllist)
{
enroll.EnrollmentSubjects.Remove(obj);
em.EnrollmentSubjects.Remove(obj);
}
}