首页 > 解决方案 > 访问具有 InverseProperty 注释的模型属性会导致 NullReferenceException

问题描述

注意:我确实从 .Find(id)“查询”中得到了有效的结果。当我访问“帖子”字段时,会引发 NullReferenceException。

我有 2 个模型类“Post”和“Thread”:

public class Post
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Text { get; set; }
    public User User { get; set; }
    public Thread Thread { get; set; }
}

public class Thread
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }         
    public string Title { get; set; }
    public Section Section { get; set; }
    [InverseProperty("Thread")]
    public List<Post> Posts { get; set; }
}

据我了解,我应该能够通过访问属性“帖子”来获取链接到线程的所有帖子条目。

使用以下代码,我尝试访问该属性:

using (var dbcontext = new DataBaseContext()) // I get a connection to the database
{
    Thread thread = dbcontext.Thread.Find(id); // I get a row from the table

    foreach(var post in thread.Posts) // It's *here* that the exception is thrown
    {
        // do something with that data
    }                    
}

结果是我得到了 NullReferenceException。我认为访问 Posts 属性(最初为 null,因为它不在数据库中)会导致延迟加载(因为它具有 InverseProperty 注释)。

标签: c#.net-coreentity-framework-core

解决方案


推荐阅读