1

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();
  1. I get an error telling me I can't re-create a school with the same ID
  2. 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!

5
  • 1
    Make sure you're using the same DbContext Commented Oct 31, 2016 at 21:51
  • 1
    @CodeNotFound ... OH MY DAYS...YOU HAVE GOT TO BE ******* KIDDING ME! :@ - I changed AddTransient to AddSingleton on my DbContext and Repos and it works GRRRRRRRRRR!!! - WHERE IS THE DOCUMENTATION FOR THIS!!?!?!?! Commented Oct 31, 2016 at 21:55
  • :D Add your own answer and accept it as an answer. So future developer will know how to solve this issue ;-) Commented Oct 31, 2016 at 21:56
  • 1
    To be fair to those that aren't using DI, another option is to Attach the student and teacher objects to the context before saving the course. Attach tells EF that the object already exists in the database and shouldn't be added again. Commented Oct 31, 2016 at 22:03
  • @DStanley thank you, this is useful information which I am going to duplicate (excuse the pun) in my answer :) Commented Oct 31, 2016 at 22:04

1 Answer 1

3

With many thanks to CodeNotFound who deserves a trophy for...

Make sure you're using the same DbContext

So I changed AddTransient<,> to AddSingleton<,> in my services config and hey-presto! IT WORKS!

Also thanks to D Stanley for this useful snippet:

To be fair to those that aren't using DI, another option is to Attach the student and teacher objects to the context before saving the course. Attach tells EF that the object already exists in the database and shouldn't be added again.

Please, if you find this, spare a thought for those who went before you!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.