I have an entity that links to lots of entities around it. Those entities only link back to the main entity. I'm manually "Load()"ing every entity set on the context at startup (the context remains open in a static class) and I've tried this with lazy loading on and off and both result in the same exception.
If I look at the core entity at run time (Person entity), any related entities that have one or more related records work fine. Any where there are no related records for the related entity (i.e. count = 0) raises a NullReferenceException?! Here is the stack trace for the exception:
at System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.TryGetCachedRelatedEnd(String relationshipName, String targetRoleName, RelatedEnd& relatedEnd)
That's it, that's the whole stack trace.
Here is a screenshot of the data to show you what I mean:
"Addresses" works because it has a related record.
"Employees" works because it has a related record.
"Employments" does not work because there are no records but it should say Count = 0 not null reference exception?!
FYI "ActiveHours" and "ActiveEmployments" both work off "Employments" and are added to the entity via a partial class.
The code that throws the exception is:
this.Employments.Where(employment => employment.IsActive);
When I breakpoint it, Employments creates the NullReferenceException - so it is in Microsoft's Entity Framework code (as shown in the stack trace).