title: LINQ Lambda only select if exists
body: <p>I am using NHibernate which is abstracted away using Respositories and services.  We are not allowed to Lazy Load properties, so they have to be selected in the query.</p>
  
  <p>My issue is that I am trying to get the most recent response number from the Answers table, but in many cases the object might not exist, so I am stuck with getting Null Reference exceptions, or "Code should be unreachable" exceptions.</p>
  
  <p>Here is what i'm doing with the approprtiate sections commented.
  .</p>
  
  <pre><code>var leaders = 
      _storeService.GetAll()
                   .Where( p =&gt; p.Id.Equals(storeId) &amp;&amp; p.Employees.Any() )
                   .SelectMany(p =&gt; p.Employees)
                   .Select(emp =&gt; new
                    {
                        LeaderId = emp.Id,
                        LeaderFirstName = emp.FirstName,
                        LeaderLastName = emp.LastName,
                        Followers = emp.Followers
                                       .Select(followers =&gt; new
  
  {
      followers.FollowerEmployee.Id,
      followers.FollowerEmployee.FirstName,                    
      followers.FollowerEmployee.LastName,
      DepartmentName = followers.FollowerEmployee.Department.Name,
  
      //Problem Area
      AssessmentResponse = followers.FollowerEmployee
                                    .Answers
                                    .First( a =&gt; a.Answer.Question.IsPrimary )
                                    .Answer
                                    .Number
                                    //Null Reference Exception                                        
  } )
  
  } ).ToList();
  </code></pre>
  
  <p>I've probably tried 15 iterations of this, not always using .First but sometimes .Single</p>
  
  <p>I don't have access to the repository pattern or any of the NHibernate queries.  Is there a way to avoid this null reference exception with LINQ?  I can't lazy load, so it's a bit of an issue.</p>