Skip to content
Advertisement

SQL Query to LINQ (use join with two keys)

I have got SQL Query and trying to use LINQ because if EF. Can someone have a look at it tell me where is my mistake, please? SQL Query is working but LINQ returns no data. Basically there is two table A and Table B. I want to do join AB which is (Bring me Data exist in Table A but not in Table B)

SqlQueryText = "  SELECT A.EmployeeID" +
               "  FROM EmployeeCourseModels A " +
               "  LEFT JOIN EmployeeTrainingModels B " +
              "   ON A.EmployeeID = B.EmployeeID and a.CourseID = B.CourseID" +
              "   WHERE(B.CourseID is null and B.EmployeeID is null) AND A.CourseID = " + courseID;

I tried this but not working. I need two key values to match when i join two tables as you can see from SQL table.

var ReqList = from course in employeeCourseRepository.EmployeeCourseList
              join training in employeeTrainingRepository.EmployeeTrainingList
              on new { c = course.CourseID, e = course.EmployeeID } equals new { c = training.CourseID, e = training.EmployeeID }
              where  (course.CourseID == Blist.CourseID)
                           select new  {  empID = course.EmployeeID };

Advertisement

Answer

Your original query is LEFT JOIN while your code is INNER one, change it into:

var ReqList = from course in employeeCourseRepository.EmployeeCourseList.Where(c => c.CourseID == Blist.CourseID)
              join training in employeeTrainingRepository.EmployeeTrainingList
              on new { c = course.CourseID, e = course.EmployeeID } equals new { c = training.CourseID, e = training.EmployeeID } into j
              from res in j.DefaultIfEmpty()
              select new  {  empID = course.EmployeeID };
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement