Reputation:
I'm a beginner and trying to create a many to many relation using a post request to user
/ApplyCourse/?studentId=1003&courseId=3
but I get the following error:
SqlException: Violation of PRIMARY KEY constraint 'PK_StudentCourses'. Cannot insert duplicate key in object 'dbo.StudentCourses'. The duplicate key value is (1003, 3).
What am I doing wrong? What is a good approach to create many to many relations?
[Route("CourseApply")]
[HttpPost("{studentId}/{courseId}")]
public async Task<IActionResult> 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<StudentCourse> Students { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public IList<StudentCourse> Courses { get; set; }
}
Upvotes: 0
Views: 2346
Reputation: 10078
Your primary key is composite: StudentId, CourseId
. You already have combination of StudentId = 1003; CourseId = 3
in the database; so you can't insert another row with the same values.
You need to decide whether you want to allow such duplicates - then create a separate key column (call it Id
or StudentCourseId
and entity framework will automatically use it as primary key). Or if you disallow duplicate combinations of Student / Course then you need to handle such error (for example, by redirecting the user to update existing record, rather than inserting a new one)
Personally, I try to avoid composite keys... but I guess, it's a matter of preference
Upvotes: 1