I'm building an exercise web API backend which connects to a MySQL database with courses and subjects. I'm using EntityFrameworkCore 7 to communicate with the database, with the code-first approach. For some reason my code fails to read a many-to-many relations table.
The database contains tables: Courses
, Subjects
, Coursesubjects
.
A course can contain multiple subjects (eg. a Maths course can have subjects about functions, matrices, sets etc).
A subject can belong to multiple courses (eg. a functions subject can belong to Maths and Physics).
Hence the third table - Coursesubjects
- contains the many-to-many relations between entities from the Courses
and Subjects
tables.
When I call the method to get all subjects related to a specific course, it fails without any error. Reading specific entities from Courses
or Subjects
works fine.
public async Task<IEnumerable<SubjectDto>> GetSubjectsForCourseAsync(string courseId)
{
var data = await _dbContext.CourseSubjects.Where(c => c.CourseId == courseId)
.Include(m => m.Subject)
.Include(m => m.Course)
.Select(s => new SubjectDto()
{
Id = s.Subject.Id,
Title = s.Subject.Title,
Description = s.Subject.Descrip,
}).ToListAsync();
return data;
}
What is wrong in my code?
So it turns out the problem was that my class was called CourseSubjects
but the table for it in the database was called Coursesubjects
and this caused the mismatch.
The solution was to wrap the code in the method within a try-catch block and then see the error message.
try
{
data = await _dbContext.CourseSubjects.Where(c => c.CourseId == courseId)
.Include(m => m.Subject)
.Include(m => m.Course)
.Select(s => new SubjectDto()
{
Id = s.Subject.Id,
Title = s.Subject.Title,
Description = s.Subject.Descrip,
}).ToListAsync();
}
catch (Exception ex) { Console.WriteLine(ex.Message); }