简体   繁体   中英

ASP.NET MVC C# list inside list

I'm using ASP.NET MVC to that enables user to takes exams, each exam contains a list of questions and each question contain multiple answer to form a multiple choice question. Here are my model

 public class Exam
{
    [Key]
    public string ExamID { get; set; }
    public string Name { get; set; }
    public Class Class { get; set; }
    public int Time { get; set; }
    public DateTime Deadline { get; set; }
    public virtual ICollection<Question> Questions { get; set; }
    
    public bool Suffer { get; set; }
}
public class Question
{
    public int ID { get; set; }
    public string question { get; set; }
    public ICollection<String> Answer { get; set; }
    public int CorrectAns { get; set; }
}

It seems fine when I create exam with multiple questions, but when I want to get my list of answers from question, it returns null for my Answer list.Does C# allows to put a list inside a list or it comes from another issue?

This is my code for create and get exam i use in controller: [HttpPost]

    public JsonResult Create(Exam exam,string ClassID)
    {
        if (exam.Time.ToString()!=null  ||exam.Deadline==null)
        {
            exam.Deadline = new DateTime(1990,1,1);
        }       
        Class @class = db.Classes.FirstOrDefault(x => x.ClassID == ClassID);          
        exam.Class = @class;
        exam.ExamID = ClassID +exam.Name;
        db.Exams.Add(exam);
        int a=db.SaveChanges();    
        return Json(a);
    } 
 public ActionResult Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Exam exam = db.Exams.Find(id);
 
        if (exam == null)
        {
            return HttpNotFound();
        }
        foreach(Question question in exam.Questions)
        {
            Debug.WriteLine(question.Answer.Count);
        }

I use Debug.WriteLine to check whether there is any answer string in question and it returns null in this step

It seems that you use Eager loading. So you have to use Include method. In order have multiple levels of depth you have to use ThenInclude after Include method.

db.Exams.Include(x => x.Questions).ThenInclude(y => y.Answers).FirstOrDefault(x => x.ExamID == id);

Official docs:https://docs.microsoft.com/en-us/ef/core/querying/related-data/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM