❔ Troubleshooting EF Core: Error Message - INSERT Statement Conflicts with FOREIGN KEY Constraint

Hey there facing an issue,
I got a lesson entity that contains a List of questions.
Mapping is done like this:
             b.HasMany(x => x.Questions).WithOne(x => x.Lesson).HasForeignKey(x => x.LessonId).IsRequired();

I am getting an exception when attempting to insert a new lesson, and my assumption is that the foreign key constraint on the questions array is failing because the lesson does not yet have an ID. As a result, the questions array is missing the required foreign key reference to the newly created lesson. Here is an example of the JSON data I am using:
{

  "lessonNumber": 0,
  "lessonDifficulty": 0,
  "questions": [
    {
      "questionText": "string",
      "questionNumber": 0
    }
  ],
  "lessonName": "string"
}


Method like this:
        public async Task<LessonDTO> CreateAsync(CreateLessonDTO input)
        {
            try
            {
                var lessonCount = await _lessonRepository.CountAsync(x => x.CreatorId == CurrentUser.Id);
                var lesson = ObjectMapper.Map<CreateLessonDTO, Lesson>(input);
                lesson.LessonNumber = lessonCount + 1;
                lesson.CreatorId = CurrentUser.Id;
                lesson.isServerGenerated = false;
                lesson = await _lessonRepository.InsertAsync(lesson);
                _activeLesson=lesson;
                await UpdateLessonStateAsync(true);
                UpdatePrivateFields(lesson);

                return ObjectMapper.Map<Lesson, LessonDTO>(lesson);
            }
            catch (Exception ex)
            {
                // Handle the exception here, or re-throw it if appropriate
                throw new Exception("An error occurred while creating the lesson.", ex);
            }
        }
Was this page helpful?