How can I make a left join
with some conditions using LINQ lambda expressions?
In SQL Server I have this query:
select usr.Id, usr.FirstName, usr.LastName, ex.Id
from User usr
left join Exam ex on ex.Id = usr.IdExam
and (ex.Id is null or (ex.InitialDate is null or ex.InitialDate >= getdate())
and (ex.EndDate is null or ex.EndDate <= getdate()))
But I need to do it in C # and tried to do this with GroupJoin
:
dataModel.User
.GroupJoin(dataModel.Exam,
usr => usr.IdExam, ex => ex.Id,
(usr, ex) => new { Usr = usr, Ex= ex})
.DefaultIfEmpty()
.SelectMany(final => final.Exam.Where(ex => ex == null ||
((!ex.InitialDate.HasValue || DateTime.Compare(ex.InitialDate.Value, DateTime.Now) <= 0)
&& (!ex.EndDate.HasValue || DateTime.Compare(ex.EndDate.Value, DateTime.Now) >= 0))),
(final, ex) => new
{
IdUser = final.Usr.Id,
FirstName = final.Usr.FirstName,
LastName = final.Usr.LastName,
IdExam = ex.Id
}).ToList();
The problem is that in C # the expression is returning less data than the query in SQL. What am I doing wrong?