根据子值过滤Entity Framework中的查询

时间:2010-09-22 20:59:21

标签: c# .net entity-framework entity

我在实体框架(EF)中设置了一个模型,其中有两个表,父和子,在一对多的关系中。我遇到麻烦的地方是用linq写一个查询,我试图检索父项的单个实例,同时过滤父项中的字段和子项中的另一个字段。它看起来像下面列出的内容:

var query = from c in context.ParentTable 
            where c.IsActive == true && c.ChildTable.Name = "abc" 
            select c;

不幸的是,当我尝试这个时它会失败,因为当我输入c.ChildTable时,没有名为“Name”的字段可通过Intellisense出现。

任何指导都将不胜感激。

1 个答案:

答案 0 :(得分:3)

这是正确的,因为 c.ChildTable 不是 Child 类型,而是 EntityCollection< Child> 。为了使您的查询有效,您需要像这样修改它:

var query = from p in context.ParentTable 
            from c in p.ChildTable 
            where p.IsActive == true 
                  && c.Name == "abc" 
            select p;