我有以下LINQ表达式:
public IList<Objective> GetObjectives(int examId)
{
var objectives = _objectivesRepository
.GetAll()
.Where(o => o.ExamId == examId || examId == 0)
.Include(o => o.ObjectiveDetails)
.ToList();
return objectives;
}
public partial class Objective
{
public int ObjectiveId { get; set; }
public int ExamId { get; set; }
public int Number { get; set; }
public virtual ICollection<ObjectiveDetail> ObjectiveDetails { get; set; }
}
public partial class ObjectiveDetail
{
public int ObjectiveDetailId { get; set; }
public int ObjectiveId { get; set; }
public int Number { get; set; }
public string Text { get; set; }
}
如何修改此表达式,以便按Number
的顺序返回目标,并按Number
的顺序返回ObjectiveDetails?
答案 0 :(得分:2)
你可以在这里使用投影,例如
var objectives = _objectivesRepository
.GetAll()
.Where(o => o.ExamId == examId || examId == 0)
.Include(o => o.ObjectiveDetails)
.Select(x => new Objective {
ObjectiveId = x.Id,
ExamId = x.ExamId,
Number = x.Number,
ObjectiveDetails = x.ObjectiveDetails.OrderBy(d => d.Number).ToList()
})
.OrderBy(x => x.Number)
.ToList();
return objectives;
答案 1 :(得分:2)
public IList<Objective> GetObjectives(int examId)
{
var objectives = _objectivesRepository
.GetAll()
.Where(o => o.ExamId == examId || examId == 0)
.Include(o => o.ObjectiveDetails.OrderBy(d => d.Number))
.OrderBy(o => o.Number);
.ToList();
return objectives;
}
答案 2 :(得分:1)
不幸的是,您必须与主查询分开对嵌套对象进行排序。我不相信有一种方法可以使Include
语句按顺序检索元素。
public IList<Objective> GetObjectives(int examId)
{
var objectives = _objectivesRepository
.GetAll()
.Where(o => o.ExamId == examId || examId == 0)
.Include(o => o.ObjectiveDetails)
.ToList();
return objectives.OrderBy(o => o.Number)
.Select(o => {
var record = o;
record.ObjectiveDetails = record.ObjectiveDetails.OrderBy(d => d.Number).ToList();
return record;
});
}