Linq to Entities - 过滤子表

时间:2011-06-29 12:21:59

标签: linq-to-entities

我的Edmx,Categories和Items中有两个表。 items表有一个“Visible”bool字段。

我想返回带有附加Items表的categories表,其中只有Visible = True的记录。

您能举例说明如何仅返回Visible = True的项目吗?

我尝试了以下没有效果的

var categoryList =来自db.Categories中的cl                                    其中cl.Items.Any(item => item .Visible == true)                                    选择cl

由于

标记

SQL查询是:

ADO.NET:Execute Reader“SELECT [Extent1]。[ID] AS [ID], [Extent1]。[Category_Name] AS [Category_Name], [Extent1]。[CategoryNote] AS [CategoryNote], [Extent1]。[CategoryOrder] AS [CategoryOrder] FROM [dbo]。[Categories] AS [Extent1] 在哪里(选择     1 AS [C1]     FROM [dbo]。[Items] AS [Extent2]     WHERE([Extent1]。[ID] = [Extent2]。[CategoryID])AND([Extent2]。[Visible] IS NOT NULL)AND([Extent2]。[Visible] = 1) )” 命令文本“SELECT [Extent1]。[ID] AS [ID], [Extent1]。[Category_Name] AS [Category_Name], [Extent1]。[CategoryNote] AS [CategoryNote], [Extent1]。[CategoryOrder] AS [CategoryOrder] FROM [dbo]。[Categories] AS [Extent1] 在哪里(选择     1 AS [C1]     FROM [dbo]。[Items] AS [Extent2]     WHERE([Extent1]。[ID] = [Extent2]。[CategoryID])AND([Extent2]。[Visible] IS NOT NULL)AND([Extent2]。[Visible] = 1) )“已在连接上执行

1 个答案:

答案 0 :(得分:1)

你的代码应该工作!!

尝试以下代码:

db.Categories.Where(c => c.Items.Any(i => (bool)i.Visible)).Select(c => c)

运行SQL事件探查器/ IntelliTrace以检查生成的代码。

编辑:我修改了代码 EDIT2:检查此代码(我颠倒了查询)

db.Items.Where(i => i.Visible != null && (bool)i.Visible).SelectMany(i => i.Categories);