【问题标题】:Entity Framework .Include throwing NullReferenceException实体框架。包括抛出 NullReferenceException
【发布时间】:2018-07-21 02:40:46
【问题描述】:

我有一个非常基本的 EF 设置,在尝试使用 .Include 填充导航属性时抛出一个奇怪的错误。以下是实体模型:

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; }
}

我通过注入的数据库上下文使用这些,并且可以在不使用导航属性的情况下很好地查询每个。我也可以查询 LineGroups 并包含 LineGroupMembers 属性就好了,就像这样:

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

这会将所有线路组加载到一个列表中,该列表对于每个线路组都有一个正常工作的“LineGroupMembers”集合。但是,如果我尝试

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

我得到“NullReferenceException”,但没有任何有用的细节。任何想法为什么导航属性将以一种方式而不是另一种方式工作?两个数据库表中都没有空值...

【问题讨论】:

    标签: c# entity-framework asp.net-core-2.0


    【解决方案1】:

    将您的导航属性设为public

    public LineGroup LineGroup { get; set; }
    

    如果是internal,EF 默认不会接收到。您还可以添加显式流畅映射以强制 EF 也识别它。

    【讨论】:

    • 有效,虽然内部的最初用途是为了防止 json 序列化的自引用错误。由于某种原因,正常的“SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore”没有解决这种情况。但是,在公开后将 [jsonignore] 添加到 LineGroup 属性将满足我的需要。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多