Thildemar
Thildemar

Reputation: 99

Entity Framework .Include throwing NullReferenceException

I have a very basic EF setup that is throwing an odd error when trying to populate a navigation property by using .Include. Here are the entity Models:

public class LineGroup
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }  
    public ICollection<LineGroupMember> LineGroupMembers { get; set; }
}

public class LineGroupMember
{
    public int ID { get; set; }
    public int Extension { get; set; }
    public string Name { get; set; }
    public int Permissions { get; set; }
    public bool IsLoggedIn { get; set; }

    public int LineGroupID { get; set; }

    internal LineGroup LineGroup { get; set; }
}

I am using these through an injected DB context, and can query each just fine without using navigation properties. I can also query the LineGroups and include the LineGroupMembers property just fine, like so:

var LineGroups = _context.LineGroups.Include(l => l.LineGroupMembers).ToList();

This load all of the line groups into a list that has a correctly working "LineGroupMembers" collection for each Line Group. However, if I try

var lineGroupMembers = _context.LineGroupMembers.Include(m => m.LineGroup).ToList();

I get "NullReferenceException" with no helpful details. Any ideas why the navigation property will work one way and not the other? There are no null values in either database table...

Upvotes: 0

Views: 1946

Answers (1)

Igor
Igor

Reputation: 62213

Make your navigation property public

public LineGroup LineGroup { get; set; }

If it is internal it won't be picked up by default by EF. You could also add explicit fluent mapping to force EF to recognize it as well.

Upvotes: 2

Related Questions