I've been trying to figure out how to translate the following LINQ query syntax to method syntax, but I just don't get it:
from exa in _context.Exams
from stu in exa.Class.Students
where exa.Id == 1
select new StudentFullName
{
Id = stu.Id,
FullName = stu.Person.FirstName " " stu.Person.LastName
}
The property ICollection<Student> Students
from the table Classes
for the many-to-many relationship with Students
is causing my confusion.
I tried this:
_context.Exams
.Where(exa => exa.Id == id)
.Select(exa => new StudentFullName
{
Id = exa.Class.Students.Select(stu => stu.Id),
FullNamee = exa.Class.Students.Select(stu => stu.Person.FirstName " " stu.Person.LastName)
}).ToList();
But I can't create the class StudentFullName
because the query returns IEnumerable<int>
instead of int
for each property.
That's what I get: https://imgur.com/a/Tp5hPHE
That's what I should get: https://imgur.com/a/PyWYQh5
EDIT: Tweaked the solution from tymtam and it worked
_context.Exams
.Where(exa => exa.Id == id)
.SelectMany(exa => exa.Class.Students
.Select(stu => new StudentFullNameViewModel
{
Id = stu.Id,
FullName = stu.Person.FirstName " " stu.Person.LastName
})
).ToList()
CodePudding user response:
It's very suspicious that:
- there is no join between students and exams
exa
is not used in the result object
A 1-to-1 translation is I think this:
var students2 = exams
.Where(exa => exa.Id == id)
.SelectMany(exa => exa.Class.Students
.Select(stu => new StudentFullName
{
Id = stu.Id,
FullNamee = stu.Person.FirstName " " stu.Person.LastName
}))
.ToList();