【发布时间】:2014-08-01 04:49:36
【问题描述】:
我有一个复杂的 LINQ 查询,我很难弄清楚。 我有一个这样的域模型:
ReviewCategory > has ReviewQuestions > has ReviewAnswers
我要做的是计算一个类别中所有问题的某个值的答案数量。我是从一个非常古老的经典 asp 系统构建的,该系统使用多个数据库存储过程来完成这项工作,但我认为它可以使用 LINQ to EF 进行管理。
我有一个 ViewModel,我正在为每个答案值设置类别名称、顺序和计数,因此视图模型将包含类别列表和响应数量的计算。
这是我坚持的代码:
pcvm.Categories = from x in _repository.GetAll<ReviewCategory>()
where x.include == true &&
((x.AuditQuestionGroupId != null ? x.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId)
from y in x.Questions
where y.include == true
from z in y.Answers
where z.entityId == this.LoggedInEntity.EntityId
orderby x.order != null ? 999 : x.order, x.name
group x by new { x.id, x.name, x.order, z.yourEvaluation, z.yourResponse } into newGroup
select new PracticeConductCategoriesViewModel
{
Id = newGroup.Key.id, // The categoryId
Name = newGroup.Key.name, // The category name
Order = newGroup.Key.order, // The category order
EvaluationNR = newGroup.Key.yourEvaluation, // The number of answers where yourEvaluation = 0
Evaluation1 = newGroup.Key.yourEvaluation, // The number of answers where yourEvaluation = 1 etc etc.
Evaluation2 = newGroup.Key.yourEvaluation,
Evaluation3 = newGroup.Key.yourEvaluation,
Evaluation4 = newGroup.Key.yourEvaluation,
Percentage = newGroup.Key.yourEvaluation // Percentage of yourEvaluations answered for each category
};
所以本质上我正在尝试对孙子的总和进行分组 价值观。我已将我要返回的值放入 cmets 进入 ViewModel,但我不知道如何计算 答案。答案应该在组中还是必须在分组后的另一个查询中?如果是这样,我如何在组后使用变量z。
我得到了错误的类别列表,因为我只得到了 已回答问题的类别。但我知道我可以使用 from/into/isdefault,所以请不要担心。
【问题讨论】:
标签: c# linq group-by linq-to-entities entity-framework-6