【问题标题】:EF6 LinQ - Select descendants where matching expressionEF6 LinQ - 选择匹配表达式的后代
【发布时间】:2018-05-28 18:54:53
【问题描述】:

我想用一个表达式过滤 School 的后代。这可能吗?我只想要“12”岁的学生

伪代码

context.Schools.Where(s => s.Name = "Springfield Elementary").Where(s => 
s.Pupils.Age == 12).Select(s);

基本上我想要一个学校集合,其中包含与我的表达相匹配的学生集合

谢谢!

【问题讨论】:

  • 你能显示你想要得到的输出吗?另外,学校的代码会很好。
  • 首先包括学生context.Schools.Include(s => s.Pupils).Where(s => s.Name = "Springfield Elementary" && s.Pupils.Age == 12).Select(s);
  • 我不能以这种方式使用 Include 语句,因为“Schools”是一个 EF 实体。也许只有通过创建匿名类型才有可能?
  • context.Pupils.Where(s => s.Age == 12 && s.School.Name == "Springfield Elementary")

标签: entity-framework linq


【解决方案1】:
context.Schools.Where(s => s.Name == "Springfield Elementary" && s.Pupils.Age == 12);

.Select(s) 学校不应该是必要的,因为这就是您要查询的内容。

这将返回学生年龄为 12 岁的学校。 但是,如果您想选择学生,则需要:

context.Schools
.Where(s => s.Name == "Springfield Elementary" && s.Pupils.Age == 12)
.Select(s=>s.Pupils);

或者按照 cmets 的建议,改为询问学生

context.Pupils.Where(s => s.Age == 12 && s.School.Name == "Springfield Elementary");

这假设学校/学生看起来像这样(代码优先 POCO):

public class School
{ 
    public int SchoolId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Pupil> Pupils { get; set; }
}

public class Pupil
{ 
    public int PupilId { get; set; }

    public int Age { get; set; }

    public int SchoolId { get; set; }
    public virtual School School { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多