我有一个asp.net mvc项目。我正在通过ajax get从数据库中获取一些问题和答案。我的查询时间太长。如何修改代码以更快地工作?
我将问题和答案存储在单独的表格中。每个答案都是与ID相关的问题。
感谢您的回答。
我的观点:
$.ajax({//GET QUESTIONS
url: '@Url.Action("GetQuestionsBySubCategory", "Order")',
type: "GET",
data: { subcattext : selectedSubCategory },
success: function (result) {
$('<div class=\"form-group\" id=\"sorularform\" ><input name=\"altcat\" value=\"' + selectedSubCategory + '\" type=\"hidden\">').prependTo("#sorular");
// loop each question
for (var i = 0; i < result.length; i++) {
//IF QUESTION 1 START
if (result[i].QuestionType == 1) {
$('<label for=\"exampleFormControlSelect' + i + '\" > ' + result[i].Description + '</label ><select name=\"' + result[i].Description + ' \" class=\"form-control\" id=\"exampleFormControlSelect' + result[i].Id + '\"></select>').appendTo("#sorularform");
var questionid;
$.ajax({//GET ANSWERS
url: '@Url.Action("GetAnswersByQuestionId", "Order")',
type: "GET",
data: { questionid: result[i].Id },
success: function (answerresult) {
for (var a = 0; a < answerresult.length; a++) {
$('<option>' + answerresult[a].Description + '</option>').prependTo("#exampleFormControlSelect" + answerresult[a].Question_Id);
}
},
error: function (err) {
// the call thrown an error
console.log("Hata Oluştu")
},
complete: function () {
//$(".loading").hide();
}
});
};
}
},
error: function (err) {
// the call thrown an error
console.log("Hata Oluştu")
},
complete: function () {
//$(".loading").hide();
$("</div>").appendTo(".form-group");
$('#yersec').insertBefore('#sorularform');
//$('#sorular').html(table);
}
});
Controller.cs
public ActionResult GetQuestionsBySubCategory(string subcattext)
{
var subcatid = subCategoryServices.GetAll().Where(x => x.Title == subcattext).FirstOrDefault().Id;
IEnumerable<QuestionVM> questionList = questionServices.GetAll().Where(x => x.SubCategory_Id == subcatid);
return Json(questionList, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult GetAnswersByQuestionId(int questionid)
{
IEnumerable<AnswerVM> answerList = answerServices.GetAll().Where(x => x.Question_Id == questionid);
return Json(answerList, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:0)
如果您想加快查询速度,建议使用Dapper。 Dapper是一种轻量级的ORM,其运行速度几乎与本机SQL一样快。有一个很好的教程,我建议您在这里阅读:https://www.c-sharpcorner.com/article/asp-net-mvc-crud-with-dapper-micro-orm/
本质上,您将像这样运行查询(虽然不完全正确,但它非常接近Dapper语法,而看不到您的数据库结构或其他代码):
public ActionResult GetQuestionsBySubCategory(string subcattext)
{
var subcatid = db.Query("SELECT Id from SubcategoryServices WHERE Title = @title", new { title = subcattext });
IEnumerable<QuestionVM> questionList = db.Query("SELECT * FROM QuestionServices WHERE SubCategory_Id = @subcategoryId", new { subcategoryId = subcatid });
return Json(questionList, JsonRequestBehavior.AllowGet);
}
放在一边-您的DOM操作也很慢,因此也可能使您的应用程序变慢。技术原因是因为在将元素添加到DOM之后,DOM必须重新渲染自身。渲染需要时间。