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.