0

I have a problem when converting sql to query c# about left join here is sql query

select mTeacher.Id as Id, mTeacher.Name as Name, mStudents.Name as Addresses
from Teachers mTeacher
 left join Students mStudents
    on mStudents.TeacherId=mTeacher.Id
    where mStudents.Name = 'some of word'

here is the image

and here is i converted to sql to query c#

 var zzz= from mTeacher in repo.Teachers
                      join mStudents in repo.mStudents on mTeacher.Id equals mStudents.TeacherId into a
                      from y1 in a.DefaultIfEmpty()
                      where mTeacher.Name.Equals("someofword") or mStudent.Name.Equals("somofword")
                      select new { mTeacher.Id,mTeacher.Name};

there will be student will have null value mStudent.Name.Equals("somofword") i got something like this how to handle this

Community
  • 1
  • 1

1 Answers1

0

If I go by the SQL query, your where clause is only looking up Student.Name.

This has to be not null (as per you where query). So I would suggest that you use simply an inner join. This will solve your C# conversion issue as well.

If you still want to retain the check, then you can modify your where clause to:

where mTeacher.Name.Equals("someofword") or (mStudent != null && mStudent.Name.Equals("somofword"))

The null check will make sure that you do not run into the object is null error (remember in case of left join the student value can be null).

Also add a similar null check in your select clause, if you are referring to values from student table.

 select new { mTeacher.Id,mTeacher.Name, StudentName = ( y1 == null ) ? "No Student" : y1.Name};
peeyush singh
  • 1,337
  • 1
  • 12
  • 23