2

I am trying to write a linq to sql statement that will join a total of 3 tables. table 1 = users (userId) tabe 2 = userCourses (userId, CourseId), table 3 = courses(courseId).

This is what i am trying to do:

from u in db.Users join uc in userCourse on u.userId = uc.Id
                   join c in course on uc.courseId = c.courseId

                   where u.userId = uc.userId
                   select c.name

what is the proper syntax?

072et
  • 345
  • 2
  • 8
  • 21

2 Answers2

4

You are almost there, assuming your key types match. You just need to use the equals keyword in the join clauses:

from u in db.Users join uc in userCourse on u.userId equals uc.Id
                   join c in course on uc.courseId equals c.courseId   
                   where u.userId = uc.userId
                   select c.name

This is one of the few places where LINQ is slightly odd, since we cant use the equality operator in the join clause, but need to use a keyword not used anywhere else in the language. It also means that we can't join on an arbitrary expression.

driis
  • 161,458
  • 45
  • 265
  • 341
1

Try

from u in db.Users 
join uc in userCourse on u.userId equals  uc.Id
join c in course on uc.courseId equals c.courseId

where u.userId = uc.userId
select c.name

Also refer below link

https://web.archive.org/web/20101030154925/http://blogs.msdn.com/b/tikiwan/archive/2010/06/18/linq-to-sql-inner-join-left-join-examples-tutorial-samples-the-basic.aspx

Taryn
  • 242,637
  • 56
  • 362
  • 405
DevelopmentIsMyPassion
  • 3,541
  • 4
  • 34
  • 60