Reputation: 3170
I am using Entity Framework code-first and the following two models:
public class Exam
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreationDate { get; set; }
public ICollection<Question> Questions { get; set; }
}
public class Question
{
public enum Answers
{
A,
B,
C,
D
}
public int Id { get; set; }
public string Name { get; set; }
public string AnswerA { get; set; }
public string AnswerB { get; set; }
public string AnswerC { get; set; }
public string AnswerD { get; set; }
public Answers Correct { get; set; }
}
The two models above show a relationship between Exam
and Question
; Exam
has multiple Question
s. To my understanding this relationship gets correctly created by Entity Frameworks' code-first.
However, when I try to read the questions inside an Exam
object (after supposedly being added to the database), the Exam
object shows Null
for the Questions
collection. Why does this happen? The object gets correctly created using the following create method. I have debugged through its process and the Exam
object gets its questions assigned correctly.
public ActionResult Create(ExamVM examVM)
{
// Return if no questions were selected.
if (examVM.Questions == null)
return View(examVM);
// Create database-exam object.
QuestionaireDbContext db = new QuestionaireDbContext();
Exam exam = new Exam();
exam.Questions = new List<Question>();
// Fill exam with selected questions.
foreach (QuestionVM questionVM in examVM.Questions.Where(q => q.IsSelected))
exam.Questions.Add(db.Questions.Find(questionVM.ID));
exam.Name = examVM.Name;
exam.CreationDate = DateTime.Today;
// Validate exam.
if (ModelState.IsValid)
{
db.Exams.Add(exam);
db.SaveChanges();
// Return to index if changes were applied.
return RedirectToAction("Index");
}
// Return if exam isn't valid.
return View(examVM);
}
Note that in the above method I use a "helper" model (ExamVM
) to assign the questions to the exam.
To repeat the question: why does my Exam
object return Null
for its Questions
collection when querying from the database, while it gets correctly created and supposedly also correctly added to the database?
I read the exam using the following method:
public ActionResult TakeExam(int id)
{
QuestionaireDbContext db = new QuestionaireDbContext();
Exam exam = db.Exams.Find(id);
return View("TakeExam", exam);
}
The exam holds the correct Name etc, but the collection shows to be null.
This is the DbContext
, for reference:
public class QuestionaireDbContext : DbContext
{
public DbSet<Question> Questions { get; set; }
public DbSet<Exam> Exams { get; set; }
}
Upvotes: 1
Views: 67
Reputation: 151594
You either need to enable lazy loading by making the Questions property virtual, or explicitly load the collection using
dbContext.Exams.Include(e => e.Questions)
Upvotes: 2