实体框架导航属性FirstOrDefault()

时间:2014-06-10 19:35:30

标签: c# sql sql-server linq entity-framework-5

我有以下一行:

WorkPlaces.FirstOrDefault()
    .WorkSteps.Where(x=>x.Failcodes_Id != null)
    .OrderByDescending(x=>x.Timestamp)
    .FirstOrDefault()

大约有10-20个工作场所,每个工作场所都有数千个工作步骤。我想获得每个工作场所的最后一个工作步骤。 上面的代码是linqpad的一个例子,因为我无法相信生成的sql看起来像这样:

SELECT TOP (1) 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
[Extent1].[Description] AS [Description], 
[Extent1].[Active] AS [Active], 
[Extent1].[ProductionLine_Id] AS [ProductionLine_Id], 
[Extent1].[DefaultTechnology_Id] AS [DefaultTechnology_Id], 
[Extent1].[PrinterName] AS [PrinterName], 
[Extent1].[Deleted] AS [Deleted], 
[Extent2].[Id] AS [Id1], 
[Extent1].[LoggedInUser_UserId] AS [LoggedInUser_UserId]
FROM  [dbo].[WorkPlaces] AS [Extent1]
LEFT OUTER JOIN [dbo].[WorkplaceParameterSet] AS [Extent2] ON [Extent1].[Id] = [Extent2].[WorkPlace_Id]
GO

-- Region Parameters
DECLARE @EntityKeyValue1 Int = 1
-- EndRegion
SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Timestamp] AS [Timestamp], 
[Extent1].[Description] AS [Description], 
[Extent1].[WorkPlace_Id] AS [WorkPlace_Id], 
[Extent1].[WorkItemState_Id] AS [WorkItemState_Id], 
[Extent1].[UserId] AS [UserId], 
[Extent1].[WorkItem_Id] AS [WorkItem_Id], 
[Extent1].[Technology_Id] AS [Technology_Id], 
[Extent1].[Failcodes_Id] AS [Failcodes_Id], 
[Extent1].[DrawingNo] AS [DrawingNo], 
[Extent1].[ManualData] AS [ManualData], 
[Extent1].[Deleted] AS [Deleted], 
[Extent1].[WorkItemState_Arrival_Id] AS [WorkItemState_Arrival_Id]
FROM [dbo].[WorkSteps] AS [Extent1]
WHERE [Extent1].[WorkPlace_Id] = @EntityKeyValue1

有没有办法从工作步骤中获取一行而不下载9000条记录从列表顶部选择一条?

2 个答案:

答案 0 :(得分:1)

不是单独获取每个工作区,然后在查询中获取该工作地点的工作步骤,您可以使用Select将每个工作区投影到一个查询中所需的工作步骤中:

var query = WorkPlaces.Select(workplace => workplace.WorkSteps
    .Where(x => x.Failcodes_Id != null)
    .OrderByDescending(x => x.Timestamp)
    .FirstOrDefault());

答案 1 :(得分:-1)

您应该使用IQueryable界面而不是IEnumerable。另请检查this.