0

I'm trying to join two tables using Linq to sql but, I got error with

Object reference not set to an instance of an object

I think because of FirstOrDefault() method, I changed it but the error still !!!

this is my code:

        LblCourseCode.Text = Request.QueryString["CourseCode"];

        try
        {

            var qry = from cs in db.Courses

                      join inst in db.Instructors
                      on cs.CourseId equals inst.CourseId
                      where cs.CourseCode == "@CourseCode"


                      select new 
                      {
                          //cs,
                          //inst


                          cs.CourseCode,
                          cs.CourseName,
                          cs.CourseAbout,
                          cs.CourseObjectives,
                          cs.CourseLearningOut,

                          inst.InstructorName,
                          cs.CourseImgUrl,
                          ////instr = from ins in db.Instructors
                          ////        select new { ins.InstructorName }

                      };

            //LblCourseCode.Text = qry.courseCode;
            LblCourseName.Text = qry.FirstOrDefault().CourseName;
            LblCourseAbout.Text = qry.FirstOrDefault().CourseAbout;
            LblObjectives.Text = qry.FirstOrDefault().CourseObjectives;
            LblLearningOutcomes.Text = qry.FirstOrDefault().CourseLearningOut;
            LblCourseInstructore.Text = qry.FirstOrDefault().InstructorName;

            ImageCourseAb.ImageUrl = qry.FirstOrDefault().CourseImgUrl;

        } 
        catch(Exception ex)
        {
            LblErr.Text = ex.Message;
        }

    }
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Abdullah
  • 3
  • 1

1 Answers1

1

To handle the case when the collection is empty you should add a check before querying it:

if (qry.Any())
{
        LblCourseName.Text = qry.FirstOrDefault().CourseName;
        LblCourseAbout.Text = qry.FirstOrDefault().CourseAbout;
        LblObjectives.Text = qry.FirstOrDefault().CourseObjectives;
        LblLearningOutcomes.Text = qry.FirstOrDefault().CourseLearningOut;
        LblCourseInstructore.Text = qry.FirstOrDefault().InstructorName;

}

Instead of Join you can do a nested foreach-loop, it's not pretty but maybe it will help you isolate the problem:

var qry = new List<object>();
foreach (var cs in db.Courses.Where(c => c.CourseCode == "@CourseCode"))
{
    foreach (var inst in db.Instructors)
    {
        if (inst.CourseId == cs.CourseId)
        {
            qry.Add(new 
            {
                cs.CourseCode,
                cs.CourseName,
                cs.CourseAbout,
                cs.CourseObjectives,
                cs.CourseLearningOut,
                inst.InstructorName,
                cs.CourseImgUrl,
            }); 
        }
    }
}
Christian
  • 7,433
  • 4
  • 36
  • 61