0

我有以下实体框架查询,其中有 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 件物品……我做错了什么?

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

谢谢你,米格尔

4

1 回答 1

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 => ..)

where x=> 引用您的原始.Where(x =>)内容,因此它引用您的完整对象列表,而不是您的 where 查询中的过滤列表。

于 2013-03-09T22:14:15.443 回答