在C#中打印一对多关系

时间:2018-10-14 05:33:01

标签: c# .net-core

我无法访问一对多关系,当我创建它时,它可以工作,但是当我尝试打印它时,它给我一个错误“ System.NullReferenceException:'对象引用未设置为对象的实例。” “这是它的设置方式:

-lconcert

这是很多类:

public class Question
{
    public int QuestionId { get; set; }
    public string Content { get; set; }

    public List<Answer> Answers { get; set; }
}

public class ApprovalRatingContext : DbContext
{
    public DbSet<Question> Questions { get; set; }
    public DbSet<Answer> Answers { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=TrumpGame;Trusted_Connection=True;");
    }
}

这就是我试图访问它的方式:

public class Answer
{
    public int AnswerId { get; set; }
    public string Content { get; set; }
    public string ApprovalRating { get; set; }
    public int Amount { get; set; }

    public int QuestionId { get; set; }
    public virtual Question Question { get; set; }
}

这是一个控制台应用程序。

1 个答案:

答案 0 :(得分:4)

当您从 Entity Framework Core 查询数据时,它不会自动加载相关的实体。因此questionContext.Questions会从数据库加载所有问题,但不会加载相关的Answer。因此question.Answers为null,在访问时抛出NullReferenceException

要修复此问题,您需要确保也加载了Answer EF Core 为此具有扩展方法Include。您只需要在查询中附加.Include(q => q.Answers),如下所示:

foreach (var question in questionContext.Questions.Include(q => q.Answers))
{
    // ...
}

或者,您可以使用 lazy-loading 来自动按需加载数据。看到 Loading Related Data