In my domain model I have
class School
{
public ICollection<Student> Students { get; set; }
}
class Student
{
public ICollection<Course> Courses { get; set; }
}
class Teacher
{
public ICollection<Course> Courses { get; set; }
}
class Course
{
public Student Student { get; set; }
public Teacher Teacher { get; set; }
}
Say I already have a Student and a Teacher in my database
Student ID = {C26A6D90-6D36-4CE9-9FF0-5C5BAB6994CC}
Teacher ID = {26ECCCC6-4A24-4FB2-A406-5021B693EE5E}
And then I want to create a new course
Course c = new Course(student, teacher);
repo.Add(c);
repo.Save();
- I get an error telling me I can't re-create a school with the same ID
- I get an error telling me I can't re-create a student with the same ID
basically, I'm getting the records from the database (Student & Teacher), and then trying to use them to create a new relational entity (Course)
{System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_Schools'. Cannot insert duplicate key in object 'dbo.Schools'. The duplicate key value is (78434ef7-20db-42c8-448e-08d401d04461). The statement has been terminated.
This seems to be an EF7 problem...is it just not mature enough yet - because it doesn't feel like it!
Attachthestudentandteacherobjects to the context before saving thecourse.Attachtells EF that the object already exists in the database and shouldn't be added again.