title: Violation of PRIMARY KEY constraint 'PK_StudentCourses'. Cannot insert duplicate key
body: <p>I'm a beginner and trying to create a many to many relation using a post request to user</p>
  
  <pre><code>/ApplyCourse/?studentId=1003&amp;courseId=3
  </code></pre>
  
  <p>but I get the following error: </p>
  
  <blockquote>
    <p>SqlException: Violation of PRIMARY KEY constraint 'PK_StudentCourses'. Cannot insert duplicate key in object 'dbo.StudentCourses'. The duplicate key value is (1003, 3).</p>
  </blockquote>
  
  <p>What am I doing wrong? What is a good approach to create many to many relations?</p>
  
  <pre><code>[Route("CourseApply")]
  [HttpPost("{studentId}/{courseId}")]
  public async Task&lt;IActionResult&gt; CourseApply(int studentId, int courseId)
  {
          Student studentEntity = _context.Students.Find(studentId);
          Course courseEntity = _context.Courses.Find(courseId);
  
          StudentCourse enrollment = new StudentCourse();
          enrollment.Course = courseEntity;
          enrollment.Student = studentEntity;
  
          _context.StudentCourses.Add(enrollment);
  
          await _context.SaveChangesAsync();
  
          return CreatedAtAction("GetStudent", new { id = studentEntity.Id }, studentEntity);
  }
  
  public class StudentCourse
  {
      public int StudentId { get; set; }
      public Student Student { get; set; }
  
      public int CourseId { get; set; }
      public Course Course { get; set; }
  }
  
  public class Course
  {
      public int Id { get; set; }
      public string Name { get; set; }
  
      public IList&lt;StudentCourse&gt; Students { get; set; }
  }
  
  public class Student
  {
      public int Id { get; set; }
      public string Name { get; set; }
  
      public IList&lt;StudentCourse&gt; Courses { get; set; }
  }
  </code></pre>