使用 EF SelectMany 展平列表
Flatten list with EF SelectMany
我想继续从我的项目 table 中获取所有或至少部分列,这些列与我的 TimeTrackings table.
具有一对多关系
当我创建查询时,只有所有子(TimeTracking 实体)字段出现,只有父(项目 table)的 ID。
我如何使用 SelectMany 实现有效的连接以展平列表以获取所有列或至少从两个实体中的每一个指定特定列。
下面是我正在使用的 EF 查询:
Customers.SelectMany(p => p.Projects).Where (p => p.Quote != null).SelectMany (t => t.TimeTrackings).Where (t => t.Notes != null)
下面是通过 LINQPad 生成的 SQL 查询。 请注意如何只显示 ProjectID 而不是该实体的其余关联列。
SELECT
[Extent2].[TimeTrackingID] AS [TimeTrackingID],
[Extent2].[ProjectID] AS [ProjectID],
[Extent2].[StartDate] AS [StartDate],
[Extent2].[EndDate] AS [EndDate],
[Extent2].[Notes] AS [Notes],
[Extent2].[CreatedDate] AS [CreatedDate],
[Extent2].[UpdatedDate] AS [UpdatedDate]
FROM [dbo].[Projects] AS [Extent1]
INNER JOIN [dbo].[TimeTrackings] AS [Extent2] ON [Extent1].[ProjectID] = [Extent2].[ProjectID]
WHERE ([Extent1].[Quote] IS NOT NULL) AND ([Extent2].[Notes] IS NOT NULL)
下面是查询的输出:
可能您正在寻找的是 Select
进行列投影的方法:
Customers.SelectMany(p => p.Projects)
.Where (p => p.Quote != null)
.SelectMany (t => t.TimeTrackings)
.Where (t => t.Notes != null)
.Select(x => new { x.ProjectID, x.Project.Name, x.Project.CustomerId });
您可以按如下方式构建 Linq
from c in Customers
from p in c.Projects
from t in p.TimeTrackings
where p.Quotes != null
where t.Notes != null
select new { Project = p, TimeTrack = t }
此外,可以更改 select 语句以投影单个属性
select new { ProjectId = p.Id, TimeTrackId = t.Id, Anything = p.Anything }
我想继续从我的项目 table 中获取所有或至少部分列,这些列与我的 TimeTrackings table.
具有一对多关系当我创建查询时,只有所有子(TimeTracking 实体)字段出现,只有父(项目 table)的 ID。
我如何使用 SelectMany 实现有效的连接以展平列表以获取所有列或至少从两个实体中的每一个指定特定列。
下面是我正在使用的 EF 查询:
Customers.SelectMany(p => p.Projects).Where (p => p.Quote != null).SelectMany (t => t.TimeTrackings).Where (t => t.Notes != null)
下面是通过 LINQPad 生成的 SQL 查询。 请注意如何只显示 ProjectID 而不是该实体的其余关联列。
SELECT
[Extent2].[TimeTrackingID] AS [TimeTrackingID],
[Extent2].[ProjectID] AS [ProjectID],
[Extent2].[StartDate] AS [StartDate],
[Extent2].[EndDate] AS [EndDate],
[Extent2].[Notes] AS [Notes],
[Extent2].[CreatedDate] AS [CreatedDate],
[Extent2].[UpdatedDate] AS [UpdatedDate]
FROM [dbo].[Projects] AS [Extent1]
INNER JOIN [dbo].[TimeTrackings] AS [Extent2] ON [Extent1].[ProjectID] = [Extent2].[ProjectID]
WHERE ([Extent1].[Quote] IS NOT NULL) AND ([Extent2].[Notes] IS NOT NULL)
下面是查询的输出:
可能您正在寻找的是 Select
进行列投影的方法:
Customers.SelectMany(p => p.Projects)
.Where (p => p.Quote != null)
.SelectMany (t => t.TimeTrackings)
.Where (t => t.Notes != null)
.Select(x => new { x.ProjectID, x.Project.Name, x.Project.CustomerId });
您可以按如下方式构建 Linq
from c in Customers
from p in c.Projects
from t in p.TimeTrackings
where p.Quotes != null
where t.Notes != null
select new { Project = p, TimeTrack = t }
此外,可以更改 select 语句以投影单个属性
select new { ProjectId = p.Id, TimeTrackId = t.Id, Anything = p.Anything }