使用EF SelectMany展平列表

时间:2015-04-01 04:34:47

标签: sql entity-framework linqpad

我想继续从我的Projects表中获取全部或至少一些列,这些列与我的TimeTrackings表有一对多的关系。

当我创建查询时,只有所有子(TimeTracking实体)字段出来,而且只是父项的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)

下面是查询的输出: enter image description here

2 个答案:

答案 0 :(得分:1)

您正在寻找的是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 });

答案 1 :(得分:1)

您可以按照以下

形成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 }