I'm trying to insert an entity (document) with the EF and ASP.NET. My entity model and schema is below, and I'm getting an unusual error about a foreign key mismatch on the Tutors table.
Entities in 'SchoolEntities.Courses' participate in the 'FK_Courses_Tutors' relationship. 0 related 'Tutors' were found. 1 'Tutors' is expected.
I'm re-attaching the entities in different methods, which works if there's either:, A Student ID, no parent ID and a StudentID with a parent ID. Once I add the course it fails to work. FK_Courses_Tutors is set to cascade on both.
public static void EnrolStudent(Guid studentId, Course course) {
Document doc = new Document() {
Student = new Student() { StudentID = studentId },
Course = new Course() { CourseID = course.CourseID },
OriginalFilename = course.Name,
IsDirectory = true
};
Document parentDir = FileBLL.GetDocumentByNestingLevel(doc, 1); // returns an int which is the ID of the parent directory
doc.ParentID = parentDir.DocumentID;
FileBLL.AddFileEntry(doc);
}
To add an entry, I'm using:
public static int AddFileEntry(Document document) {
using(var context = new SchoolEntities()) {
if(document.Student != null) {
var existingStudent = context.Students.Where(s => s.StudentID == document.Student.StudentID).FirstOrDefault();
context.AttachTo("Students", existingStudent);
document.Student = existingStudent;
}
if(document.Course != null) { // works without this, but I need it
var existingCourse = context.Courses.Include("Tutor").Where(c => c.CourseID == document.Course.CourseID).FirstOrDefault();
context.AttachTo("Courses", existingCourse);
document.Course = existingCourse;
}
context.AddToDocuments(document);
context.SaveChanges();
return document.DocumentID;
}
}
I'd really appreciate any help as this has been troublesome from the start.
Thanks :)