Question : foreach Object reference error c# and linq

 what I am doing wrong here? can anybody point me to the problem?
I am trying to access the parent_id (Categories2)  which sometime == null;
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
eSafetyEntities db = new eSafetyEntities();
            var cat =  from c in db.Categories
                      orderby c.CategoryId
                      select c;  /*{c.Categories1, c.Categories2,  c.CategoryId,  c.CatName}.ToString();*/

            // out put the top category menu 
            foreach (Categories c in cat)
            {
                c.Categories2Reference.Load();
                c.Categories1.Load();
                       
                if ( c.Categories2.CategoryId != null)
                {
               testLbl.Text += c.Categories2.CategoryId + "  ";                     
          }
}

Answer : foreach Object reference error c# and linq

c.Categories2 can be null. So, include a condition for that.
if (c.Categories2 != null && c.Categories2.CategoryId != null)

Also, if CategoryId within Categories2 is a value type (such as int), you dont need a null-check on it.
if (c.Categories2 != null)
will do
Random Solutions  
 
programming4us programming4us