与子实体的投影

时间:2013-03-09 21:57:57

标签: entity-framework

我有以下实体框架查询,其中有40个项目:

context.Questions
  .Where(x =>
    x.Access >= 1 &&
    x.Enabled == true
  ).ToList();

然后我尝试了如下投影:

context.Questions
  .Where(x =>
    x.Access >= 1 &&
    x.Enabled == true
  ) 
  .Select(x => new {
    Duration = x.Duration,
    Text = x.Text,
    Answers = x.Answers.Select(y => new {
      Correct = y.Correct,
      Text = y.Text
    })
  }).ToList();

在这种情况下,我得到150件物品......我做错了什么?

基本上我需要问题列表和每个问题都有一个答案列表。

谢谢你, 米格尔

1 个答案:

答案 0 :(得分:1)

试一试

context.Questions
  .Where(x =>
    x.Access >= 1 &&
    x.Enabled == true
  ) 
  .Select(u => new {
    Duration = u.Duration,
    Text = u.Text,
    Answers = u.Answers.Select(y => new {
      Correct = y.Correct,
      Text = y.Text
    })
  }).ToList();

这解决了您的问题的原因是因为在您使用

之前
.Select(x => ..)

其中x =>引用原始.Where(x =>),因此它引用了完整的对象列表,而不是查询位置的过滤列表。