【问题标题】:How to get list of data from foreign key associated table is json format in mvc如何从外键关联表中获取数据列表是mvc中的json格式
【发布时间】:2016-06-30 07:16:57
【问题描述】:

我创建了两个具有外键关联的表(问题、答案),我需要基于 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" }
   ]
}

【问题讨论】:

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


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

    • 当我在上面写作时,第二次选择@Andres Nava 时出现语法错误
    • 查询返回空值..@Andres Nava
    猜你喜欢
    • 1970-01-01
    • 2019-01-15
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2021-08-17
    • 2016-02-02
    相关资源
    最近更新 更多