Why is EF7/Core inserting duplicate records?

c# entity-framework entity-framework-core

Question

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!

1
1
10/31/2016 9:47:48 PM

Accepted Answer

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!

3
5/23/2017 12:33:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow