Scenario is:
I have Two Tables.
There is One to Many Relationship between them.
I'm trying to update Enrollment by removing childs in EnrollmentSubject And Adding New Child, I face error below when I context.SaveChanges(); in 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
Here is my code:
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();
}
}
please guide me
My problem is solved...... I was removing it from parent, childs records become Orphans with Parent=null in required relationship in which child cannot exists without parent. but I they were in the context so I also removed them from context.
if (enroll.ClassId != enrollDetail.ClassId && enroll.GroupId != enrollDetail.GroupId)
{
foreach (EnrollmentSubject obj in enrolllist)
{
enroll.EnrollmentSubjects.Remove(obj);
em.EnrollmentSubjects.Remove(obj);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.