I have a problem using a subquery inside my join operator.
I'd like to know how I can make my LINQ query better.
I want to become a query like this:
SELECT Submissions.Title, SubmissionStatusEvents.ToStatus, SubmissionStatusEvents.ToStatusId, SubmissionStatusEvents.Created, SubmissionComments.Created, Content =
CASE
WHEN SubmissionComments.Type = '1'
THEN SubmissionComments.Content
ELSE NULL
END, AspNetUsers.UserName, AspNetUsers.AvatarId , Projects.Name, Comapnies.LogoId
FROM Submissions
JOIN SubmissionComments ON SubmissionComments.Id =
(
select TOP 1 Id
From SubmissionComments
where SubmissionComments.SubmissionId = Submissions.Id
Order by SubmissionComments.Created desc
)
JOIN SubmissionStatusEvents ON SubmissionStatusEvents.Id =
(
select TOP 1 Id
From SubmissionStatusEvents
where SubmissionStatusEvents.SubmissionId = Submissions.Id
Order by SubmissionStatusEvents.Created desc
)
JOIN AspNetUsers ON SubmissionComments.CommenterId=AspNetUsers.Id
JOIN Projects ON Projects.Id = Submissions.ProjectId
JOIN Companies ON Projects.CompanyId = Companies.ID
I tried it with following LINQ:
(from submission in _ctx.Submissions
join status in _ctx.SubmissionStatusEvents on (from s in _ctx.SubmissionStatusEvents where s.IsPublic && s.SubmissionId == submission.Id orderby s.Created descending select s.Id).First() equals status.Id
join comment in _ctx.SubmissionComments on (from c in _ctx.SubmissionComments where c.IsPublic && c.SubmissionId == submission.Id orderby c.Created descending select c.Id).First() equals comment.Id
join user in _ctx.Users on comment.CommenterId equals user.Id
join project in _ctx.Projects on submission.ProjectId equals project.Id
join company in _ctx.Companies on project.CompanyId equals company.Id
where submission.SubmitterId == userId
where status.IsPublic
select new SubmissionWithLastEventChangeDto
{
Id = submission.Id,
Title = submission.Ttile,
Status = status.ToStatus,
StatusId = status.ToStatusId,
StatusChange = status.Created,
ProjectId = project.Id,
ProjectName = project.Name,
ProjectType = project.Type,
MaxPayout = project.ExceptionalPayout ?? project.CriticalPayout,
LogoId = company.LogoId,
LastComment = new LastEventChangeDto
{
UserName = user.UserName,
AvatarId = user.AvatarId,
Created = comment.Created,
Type = comment.Type,
Content = comment.Type == EntityEnum.SubmissionCommentType.Event ? comment.Content : null
}
}).ToListAsync();
However this LINQ query causes multiple queries:
I tried many things. Like using let as in this example Stack Overflow answer. My final attempt is based on this Stackoverflow answer
I also tried to use .Take(1) instead of .First()
If someone could point me in the correct direction I would be happy. Sincerely, Brecht