如何使用LINQ获取有序列表详细信息

时间:2014-12-19 03:12:59

标签: c# linq entity-framework

我有问卷类及其详细信息,问题和问题组。结构是这样的:

enter image description here

我创建详细信息视图以显示Questionnaire和详细信息。应根据Sequence中的QuestionGroup显示详细信息。使用LINQ,如何获得一份问卷,其详细信息按问题组中的顺序排序。

到目前为止,当我创建一个LINQ语法来解决这个问题时:

var questionnaire = db.Questionnaires
   .Include(q => q.QuestionnaireDetails)
   .FirstOrDefault(q => q.QuestionnaireID == questionnaireID);

我有两个问题:

1)我无法为IncludeQuestion致电QuestionGroup(急切加载)
   .Include(q => q.QuestionnaireDetails.Question)< - 错误

错误:
Cannot convert lambda expression to type 'string' because it is not a delegate type

2)在致电OrderBy之前,我无法通过Sequence致电.FirstOrDefault()。   .OrderBy(q => q.QuestionnaireDetails.Question.QuestionGroup.Sequence)< - 错误

错误:
'System.Collections.Generic.ICollection<MvcApplication1.Models.QuestionnaireDetail>' does not contain a definition for 'Question' and no extension method 'Question' accepting a first argument of type 'System.Collections.Generic.ICollection<MvcApplication1.Models.QuestionnaireDetail>' could be found (are you missing a using directive or an assembly reference?)

更新

我尝试了@JesseJames的解决方案,稍作修改:

var questionnaire = from qg in db.QuestionGroups
                    join q in db.Questions on qg.QuestionGroupID equals q.QuestionGroupID
                    join qd in db.QuestionnaireDetails on q.QuestionID equals qd.QuestionID
                    join qe in db.Questionnaires on qd.QuestionnaireID equals qe.QuestionnaireID
                    orderby qg.Sequence
                    select new Questionnaire { 
                        QuestionnaireID = qe.QuestionnaireID, 
                        Date = qe.Date,
                        Respondent = qe.Respondent,
                        QuestionnaireDetails = qe.QuestionnaireDetails };

但我有错误:

The entity or complex type 'MvcApplication1Model.Questionnaire' cannot be constructed in a LINQ to Entities query.

1 个答案:

答案 0 :(得分:1)

var query = from qg in db.QuestionGroup
            from q in db.Questions.Where(r=>r.QuestionGroupId == qg.QuestionGroupId)
            from qd in db.QuestionnaireDetail.WHere(r=>r.QuestionId== q.QuestionId)
            from qe in db.Questionnaire.Where(r=>r.QuestinnareId == qd.QuestinnareId)
            orderby qg.Sequence
            select new { Questionnaire = q, QuestionnaireDetail = qd };

修改

您可能更喜欢这种语法

var query = from qg in db.QuestionGroup
            join q in db.Questions on qg.QuestionGroupId equals q.QuestionGroupId
            join qd in db.QuestionnaireDetail on q.QuestionId equals qg.QuestionId
            join qe in db.Questionnaire on qd.QuestinnareId equals qe.QuestinnareId
            orderby qg.Sequence
            select new { Questionnaire = q, QuestionnaireDetail = qd };