我需要一种方法来获得具有以下特定问题ID的最新答案。
以下对象类:
Teams
Store
Employee
Answer
Question
设置:
我需要运行一个报告,其中包含数据库中最新答案响应的计数。我只能考虑每位员工的最新回复,因为员工可以每10分钟更改一次回复。我不在乎是否有人回答“1”,对我来说重要的是,如果他们最近的回答是“1”。
如果是的话我会算他们,如果不是我不会。此外,还有多个问题。所以我不能只采取最新的回答,因为我也会失去其他问题。
现在我有以下内容,如果任何员工都有这样的回答,那么这实际上很重要。
var answers = _employeeService.GetAll()
.Where(p => p.Store.Teams.Any(t => t.Team.Id.Equals(teamId)))
.SelectMany(t => t.Answers)
.OrderByDescending(t => t.Answer.Created)
.GroupBy(x => new
{
AnswerId = x.Answer.Id,
AnswerNumber = x.Answer.Number,
AnswerText = x.Answer.Text,
QuestionId = x.Answer.Question.Id,
QuestionText = x.Answer.Question.Title
}).Select(x => new AnswerReport()
我怎样才能过滤下来,所以我不算两次人?如果有人回答1,2,3,4,5,他们的答案将被计算五次。
这样的事情就在我脑海里:
.SelectMany(t => t.Answers)
.OrderByDescending(t => t.Answer.Created)
.SelectMostRecent(t => t.Question.Distinct())) // clearly made up
.GroupBy(x => new
答案 0 :(得分:0)
确保您在answer实体中拥有员工ID作为属性。然后,您可以通过对问题ID和员工ID进行分组,根据每个预计组的最新创建日期获取最新记录,从而获得每个员工和问题的最新答案。
答案 1 :(得分:0)
这是我的hacky解决方案。
//Get all the possible questions in the database, with the count sent to zero
var allPossible = _assessmentService.GetAll()
.SelectMany(p => p.Answers).Select(x => new AnswerReport()
{
AnswerCount = 0,
AnswerId = x.Id,
AnswerNumber = x.Number,
AnswerText = x.Text,
QuestionId = x.Question.Id,
QuestionText = x.Question.Title
}).ToList();
foreach (var answer in allPossible)
{
/* Warning: might be too complicated for Linq2Sql */
answer.AnswerCount = _employeeService.GetAll()
.Where(e => e.Store.Teams.Any(p => p.Team.Id.Equals(teamId)))
.Where(e => e.Answers.Any(p => p.Answer.Id.Equals(answer.AnswerId)))
.Select(a => new
{
AnswerInfo = a.Answers
.Select(p => new{
AnswerId = answer.AnswerId,
QuestionId = answer.QuestionId
})
.FirstOrDefault(ans =>
ans.QuestionId.Equals(answer.QuestionId))
}).ToList()
//This .ToList() is yucky, but it's a problem with nhibernate
.Count(a => a.AnswerInfo.AnswerId.Equals(answer.AnswerId));
}