在我的Sql表中,索引主键是一个整数(1,2,3,...) 我有一个像这样的实体查询:
var pagedQAs = getAllQAs
.Where(qa => qa.Show)
.OrderByDescending(qa => qa.Code)
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(QAViewModels.Set)
.ToList();
结果排序列表如下:
1
11
12
...
2
21
22
...
3
31
32
...
显示正确的有序数字应该是什么?
修改>>>
sql中的表: Table in sql
该项目是Model First Not Code First
型号:
public class QAViewModels
{
public int Code { get; set; }
public string Question { get; set; }
public string InquirerName { get; set; }
public string InquirerEmail { get; set; }
public int VisitCounts { get; set; }
public Nullable<int> Respondent { get; set; }
public Nullable<System.DateTime> RespondDate { get; set; }
public string Answer { get; set; }
public string AnswerSummary { get; set; }
public virtual BaseMember BaseMember { get; set; }
public static QAViewModels Set(QuestionAnswer qa)
{
return new QAViewModels
{
Code = qa.Code,
Question = qa.Question,
InquirerName = qa.InquirerName,
InquirerEmail = qa.InquirerEmail,
VisitCounts = qa.VisitCounts,
Respondent = qa.Respondent,
RespondDate = qa.RespondDate,
Answer = qa.Answer,
AnswerSummary = qa.AnswerSummary,
BaseMember = qa.BaseMember
};
}
}
所有类型都基于SQL表文件数据类型
商店:
public List<QAViewModels> GetAllRawPaged(int page, int pageSize, out int count)
{
var getAllQAs = Tools.DataModel.QuestionAnswers;
count = getAllQAs.Count();
var pagedQAs = getAllQAs
.Where(qa => qa.Show)
.OrderByDescending(qa => qa.Code)
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(QAViewModels.Set)
.ToList();
return pagedQAs;
}
对QAStore中存储的数据的操作和查询
控制器:
public ActionResult CM_QAs()
{
QAStore qas = new QAStore();
int count = 0;
LabelStore ls = new LabelStore();
List<TagsViewsModel> tags = ls.GetAllTags();
List<QAViewModels> allQAs = qas.GetAllRawPaged(1, 100, out count);
return View(allQAs);
}
获取所有QuestionAnswers并传递给查看
视图:
@model List<wrrc.Models.QAViewModels>
<div>
@foreach (var qa in Model)
{
<div>
<span>
<span>Question Number
@Tools.ConvertNumerals(Convert.ToString(qa.Code))
</span>
</span>
<div>@Html.Raw(qa.Question)</div>
<div>@Tools.TruncateAtWord(qa.Answer, 500)))</div>
<a href="@Url.Action("SingleQA", "QA" >Full Description</a>
</div>
}
</div>
答案 0 :(得分:0)
您应该将Code
排序为int;
var pagedQAs = getAllQAs
.Where(qa => qa.Show)
.ToList()
.OrderByDescending(qa => int.Parse(qa.Code))
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(QAViewModels.Set)
.ToList();
此外,最好防止可能的空值或不正确的字符串来解析整数;
int val = 0;
var pagedQAs = getAllQAs
.Where(qa => qa.Show)
.ToList()
.OrderByDescending(qa => int.TryParse(qa.Code,out val) ? val : Int32.MaxValue)
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(QAViewModels.Set)
.ToList();
此外,使用此查询,您应该在客户端执行order/skip/take
操作。无法将int.TryParse
或int.Parse
转换为IQueryable形式的sql查询。因此,如果您有机会在数据库中将Code
列修改为int
,则可能是更好的解决方案。