In this post, we will go through a sample that shows how to write a LINQ statement with multiple joins.
If you are like me, I sometimes find it difficult to remember the syntax of LINQ statements because I jump from T-SQL to ASP.NET and C#.
I was searching for a sample that may show how to write a LINQ statement with multiple join
s and I had little luck finding it, so finally, after I put my few brain cells in action, I came up with the following:
var dbRegCourses = (from a in db.CourseRegistries
join b in db.Courses on a.courseid equals b.id
join c in db.aspnet_Users on a.userid equals c.UserId
where a.userid == sUserID
orderby a.regdate, b.code, b.description,
b.instructor, b.date, b.venue
select new
{
a.regdate, b.code, b.description,
b.instructor, b.date, b.venue});
if (dbRegCourses.Count() > 0)
{
ResultLbl.Text = "We found that you are registered to: " +
dbRegCourses.Count().ToString() + " Courses.";
return;
}
If you notice, here we are joining three tables, using a where
statement and then picking and choosing columns from at least two tables.
I also added an if
statement bottom to see if I got any rows back from the LINQ Statement and if that's the case, return a message.
Hope this helps somebody out there,
Will