简体   繁体   English

实体框架.include抛出NullReferenceException

[英]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. 我有一个非常基本的EF设置,当尝试使用.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: 我还可以查询LineGroups并包括LineGroupMembers属性,就像这样:

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. 这会将所有线路组加载到一个列表中,该列表具有每个线路组正确工作的“ LineGroupMembers”集合。 However, if I try 但是,如果我尝试

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

I get "NullReferenceException" with no helpful details. 我收到“ NullReferenceException”,没有任何有用的详细信息。 Any ideas why the navigation property will work one way and not the other? 有什么想法为什么导航属性会以一种方式而不是另一种方式起作用? There are no null values in either database table... 任何一个数据库表中都没有空值...

Make your navigation property public public您的导航属性

public LineGroup LineGroup { get; set; }

If it is internal it won't be picked up by default by EF. 如果它是internal ,则默认情况下不会被EF接收。 You could also add explicit fluent mapping to force EF to recognize it as well. 您还可以添加显式的流利映射,以强制EF也识别它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM