如何从外键关联表中获取数据列表是mvc

时间:2016-06-30 07:16:57

标签: c# sql json asp.net-mvc linq

我用外键关联创建了两个表(问题,答案),我需要基于questionID列的答案列表,因为我需要linq查询。我是mvc的初学者,任何人都可以帮助我

  

控制器代码:

public JsonResult displayQuestion()
{
     var result = from q in Db.questions
                  join a in Db.answers on q.Qid equals a.questionID
                  select new { q.QText, q.Qid, a.answer1 };
     return Json(result, JsonRequestBehavior.AllowGet);
}

json结果:

[
    {"QText":"result of 2+2","Qid":2,"answer1":"2"},
    {"QText":"result of 2+2","Qid":2,"answer1":"4"},
    {"QText":"result of 2+2","Qid":2,"answer1":"6"},
    {"QText":"result of 2+2","Qid":2,"answer1":"8"}
]

但我需要如下:

{
   "QText": "result of 2+2",
   "Qid": 2,
   "answer1": [
      { "option1": "2" },
      { "option1": "4" },
      { "option1": "6" },
      { "option‌​1": "8" }
   ]
}

1 个答案:

答案 0 :(得分:0)

不要进行连接,而是获取所需的问题信息,然后执行子查询以获取特定问题的答案:

public JsonResult displayQuestion()
{
     var result = from q in Db.questions
                  select new { 
                    q.QText, 
                    q.Qid, 
                    answer1 = (from a in Db.answers 
                               where a.questionID == q.Qid
                               select new { option1 = a }).ToList()
                  };

     return Json(result, JsonRequestBehavior.AllowGet);
}