CodexBloom - Programming Q&A Platform

LINQ Query scenarios: how to to Project Nested Collections from Entity Framework Core

👀 Views: 239 💬 Answers: 1 📅 Created: 2025-06-14
csharp linq entity-framework-core

I'm trying to implement I'm working on a personal project and I'm working with an scenario with a LINQ query in my Entity Framework Core application where I want to project nested collections into a DTO (Data Transfer Object) but keep getting an `InvalidOperationException` stating that the entity type 'Student' want to be tracked because it is not in the DbContext. I have a `Course` entity that includes a collection of enrolled `Students`, and I'm trying to create a list of courses along with their enrolled students, but the nested collection is causing issues. Here’s a simplified version of my entities: ```csharp public class Course { public int CourseId { get; set; } public string CourseName { get; set; } public virtual ICollection<Student> Students { get; set; } } public class Student { public int StudentId { get; set; } public string StudentName { get; set; } } ``` And here’s the LINQ query I’m using: ```csharp var courses = await _context.Courses.Include(c => c.Students).Select(c => new CourseDto { CourseId = c.CourseId, CourseName = c.CourseName, EnrolledStudents = c.Students.Select(s => new StudentDto { StudentId = s.StudentId, StudentName = s.StudentName }).ToList() }).ToListAsync(); ``` I’ve confirmed that the `Students` collection is properly populated when I fetch the courses, but this behavior seems to pop up when I attempt to project them into the `CourseDto`. I've tried using `.AsNoTracking()` on the context, but it hasn’t resolved the scenario. Here's the exception I'm getting: ``` InvalidOperationException: The entity type 'Student' want to be tracked because it is not in the DbContext. ``` I’m using Entity Framework Core 6.0. Can anyone guide to understand why this is happening and how I can properly project my nested collections without working with this exception? I'm working on a API that needs to handle this. Has anyone else encountered this?