0

I am unable to access a one to many relationship, when I create it it works, but when I try to print it, it gives me an error " System.NullReferenceException: 'Object reference not set to an instance of an object.' " This is how it is setup:

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

This is the many class:

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

And this is how im trying to access it:

ApprovalRatingContext questionContext = new ApprovalRatingContext();
foreach (var question in questionContext.Questions)
{
    Console.WriteLine(question.Content);

    List<Answer> answers = question.Answers;

    foreach (Answer answer in answers)
    {
        Console.WriteLine(answer.Amount);
    }

}

Console.ReadLine();

This is a console application.

ekad
  • 14,436
  • 26
  • 44
  • 46
Mario Landa
  • 67
  • 1
  • 7
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Sir Rufo Oct 14 '18 at 06:39

1 Answers1

4

When you query data from Entity Framework Core, it doesn't load related entities automatically. So questionContext.Questions loads all questions from database, but related Answers are NOT loaded. Therefore question.Answers is null and throws NullReferenceException when accessed.

To fix it, you need to ensure that Answers are loaded too. EF Core has extension method Include for this purpose. You just need to append .Include(q => q.Answers) to your query like this:

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

Alternatively, you can use lazy-loading to load data automatically on-demand. See Loading Related Data

Ňuf
  • 6,027
  • 2
  • 23
  • 26