Linq left join on nullable field
<p>In the following example I have entity1, where the user_id is a nullable int, and sometimes its indeed null. Entity2 is something like a bridge to connect entity1 to entity3, via the <strong>user_id</strong>, to get the <strong>person_id</strong> and eventually the corresponding <strong>fullname</strong>.</p>

<p>My goal would be to write a linq query in which if entity1's user_id is null, then don't throw a NullReferenceException, but get null for the fullname property.</p>

<p>Given the entities below, I would expect my query to return this:</p>

<ul>
<li>codeOfEntity = "21006.040",  fullname = null</li>
<li>codeOfEntity = "14006.010",  fullname = "John Smith"</li>
<li>codeOfEntity = "21006.020", fullname = null</li>
<li>codeOfEntity = "35716.001",  fullname = "Dave Doe"</li>
<li>codeOfEntity = "11153.013",  fullname = "Zach White"</li>
</ul>

<p><strong>Entities:</strong></p>

<pre><code>class entity1
{
    public int? user_id { get; set; }
    public string codeOfEntity { get; set; }
}

class entity2
{
    public int user_id { get; set; }
    public int person_id { get; set; }
}

class entity3
{
    public int person_id { get; set; }
    public string fullname { get; set; }
}
</code></pre>

<p><strong>And filled up like:</strong></p>

<pre><code>var listOfEntity1 = new List&lt;entity1&gt;()
{
    new entity1() { user_id = null, codeOfEntity = "21006.040" },
    new entity1() { user_id = 10, codeOfEntity = "14006.010" },
    new entity1() { user_id = null, codeOfEntity = "21006.020" },
    new entity1() { user_id = 1, codeOfEntity = "35716.001"},
    new entity1() { user_id = 4, codeOfEntity = "11153.013" }
};

var listOfEntity2 = new List&lt;entity2&gt;()
{
    new entity2() { user_id = 1, person_id = 100 },
    new entity2() { user_id = 4, person_id = 400 },
    new entity2() { user_id = 10, person_id = 1000 }
};

var listOfEntity3 = new List&lt;entity3&gt;()
{
    new entity3() { person_id = 100, fullname = "John Smith" },
    new entity3() { person_id = 400, fullname = "Dave Doe" },
    new entity3() { person_id = 1000, fullname = "Zach White" }
};
</code></pre>

<p><strong>My query that throws a NullReferenceException:</strong></p>

<pre><code>var result = (from e1 in listOfEntity1
              join e2 in listOfEntity2 on e1.user_id equals e2.user_id into e2Group
              from e2 in e2Group.DefaultIfEmpty()
              join e3 in listOfEntity3 on e2.person_id equals e3.person_id into e3Group
              from e3 in e3Group.DefaultIfEmpty()
              select new { e1.codeOfEntity, e3.fullname }).ToList();
</code></pre>

<p>Thank you.</p>