简体   繁体   English

ASP.NET MVC C# 列表内列表

[英]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.我正在使用 ASP.NET MVC 使用户能够参加考试,每个考试都包含一个问题列表,每个问题都包含多个答案以形成一个选择题。 Here are my model这是我的 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?当我创建包含多个问题的考试时似乎很好,但是当我想从问题中获取答案列表时,它会为我的答案列表返回 null。C# 是否允许将列表放入列表中,或者它来自另一个问题?

This is my code for create and get exam i use in controller: [HttpPost]这是我在 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我使用 Debug.WriteLine 检查是否有任何有问题的答案字符串,并在此步骤中返回 null

It seems that you use Eager loading.看来您使用的是急切加载。 So you have to use Include method.所以你必须使用 Include 方法。 In order have multiple levels of depth you have to use ThenInclude after Include method.为了获得多层次的深度,您必须在 Include 方法之后使用 ThenInclude。

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/官方文档:https://docs.microsoft.com/en-us/ef/core/querying/related-data/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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