❔ 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();
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"
}
{

"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);
}
}
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);
}
}
2 Replies
antimatter8189
antimatter8189OP2y ago
However when debuggin after this line
lesson = await _lessonRepository.InsertAsync(lesson);
lesson = await _lessonRepository.InsertAsync(lesson);
` it seems correct, lesson is coming back with a guid and its set on the question as a LessonId nobody got a clue?:D
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?