Saturday, October 8, 2011

Sample LINQ with Multiple Joins and Selected Columns

If you are like me, I sometimes find difficult remembering 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 joins 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 pick 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




No comments:

Post a Comment