1

I have a Document table and a Tenant table in my database, with a Document_Tenant table to relate the two. I'm trying to get a selection of all Documents, with related Tenants, if any. That should be a left join between Document and Document_Tenant and an inner join between Document_Tenant and Tenant, so I followed Entity framework left join to get this code:

var combinedQuery = from doc in DocumentProvider.GetDocuments()
                    join dt in CustomTableItemProvider.GetItems<Document_TenantItem>()
                         on doc.ItemID equals dt.Document_ID into ddt
                    from x in ddt.DefaultIfEmpty()
                    join t in TenantProvider.GetTenants()
                         on x.Tenant_ID equals t.ItemID    // joined tenants
                    select new { doc, t.Tenant_ID };

When that query executes, though, I get a NullReferenceException. I'm not sure why.

Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.

at lambda_method(Closure , <>f__AnonymousType372 , <>f__AnonymousType362 )
at System.Linq.Enumerable.d__233.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator
2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable
1 source)

user1269310
  • 342
  • 3
  • 13
  • Why not use navigation properties instead? And why are you getting your related tables from different places instead of all from the same context? – juharr Oct 28 '19 at 21:35

1 Answers1

1

I made a couple of mistakes in my original post. One was that this isn't actually Entity Framework, but an API similar to it. That meant I couldn't use navigation properties as suggested by Steve Py.

Also, and this is the critical one, I oversimplified my code. Where I posted select new { doc, t }, my code throwing the exception was select new { doc, t.Tenant_ID }. Since this is a left join, the t value is sometimes null - which leads to a NullReference exception.

I changed my select to read:

select new {
    Doc = doc,
    Tenant_ID = t == null ? null : t.Tenant_ID
};

Side note: I'm not sure why we can't use a null coalescing operator in the select, but we can't.

user1269310
  • 342
  • 3
  • 13
  • I had same problem in my unit test method. Tested method worked, but a test not passed and throwed an identical exception as your. Your solution helped. Thanks for sharing with this interesting scenario. – 1_bug Jul 07 '20 at 08:25