I have the following C# code generating a query on a sqlserver.
return c.Bags
.Where(b => b.RollformerId == RollformerId
&& (!b.Order.OnHold.HasValue || b.Order.OnHold.Value == false)
&& (!b.Order.Archive.HasValue || b.Order.Archive.Value == false)
&& (!b.Order.Inactive.HasValue || b.Order.Inactive.Value == false)
&& (b.BagStatus.BagStatusId == notStarted
|| b.BagStatus.BagStatusId == inProgress))
.OrderBy(b => b.Priority)
.ThenBy(b => b.ScheduleDate)
.SelectMany(b => b.Packs
.OrderBy(p => p.PackSequence))
.FirstOrDefault();
It generates the following sql code:
SELECT
[Limit1].[BatchID] AS [BatchID],
[Limit1].[RollformerID] AS [RollformerID],
[Limit1].[Description] AS [Description],
[Limit1].[OrderID] AS [OrderID],
[Limit1].[BagId] AS [BagId],
[Limit1].[PackSequence] AS [PackSequence],
[Limit1].[PackStatusId] AS [PackStatusId],
[Limit1].[Priority] AS [Priority],
[Limit1].[ProductID] AS [ProductID],
[Limit1].[DeliveryID] AS [DeliveryID]
FROM ( SELECT TOP (1)
[Extent4].[BatchID] AS [BatchID],
[Extent4].[DeliveryID] AS [DeliveryID],
[Extent4].[Priority] AS [Priority],
[Extent4].[ProductID] AS [ProductID],
[Extent4].[RollformerID] AS [RollformerID],
[Extent4].[Description] AS [Description],
[Extent4].[OrderID] AS [OrderID],
[Extent4].[BagId] AS [BagId],
[Extent4].[PackSequence] AS [PackSequence],
[Extent4].[PackStatusId] AS [PackStatusId]
FROM [dbo].[Bag] AS [Extent1]
INNER JOIN [dbo].[Orders] AS [Extent2] ON [Extent1].[OrderId] = [Extent2].[OrderID]
LEFT OUTER JOIN [dbo].[Orders] AS [Extent3] ON [Extent1].[OrderId] = [Extent3].[OrderID]
INNER JOIN [dbo].[Batches] AS [Extent4] ON [Extent1].[BagId] = [Extent4].[BagId]
WHERE ([Extent2].[OnHold] IS NULL OR [Extent3].[OnHold] = 0)
AND ([Extent3].[Archive] = 0 OR [Extent3].[Archive] IS NULL)
AND ([Extent3].[Inactive] = 0 OR [Extent3].[Inactive] IS NULL)
AND ([Extent1].[RollformerId] = @p__linq__0)
AND ([Extent1].[BagStatusId] IN (@p__linq__1,@p__linq__2))
) AS [Limit1]
Comparing the output to the original, it appears that the ordering statements have been completely ignored in the generated SQL.
Could someone please identify what is wrong with my statement to have the ordering ignored.
The solutions provided in Ordering not working in Entity Framework query did not suit this situation (at least to my satisfaction)
UPDATE:
The first set of orderby is on the main entity, where I wish to select the first one within the order, and the subsequent selectmany is on the detail records, or which I wish to get the first.
On thinking about it, the selectmany is not required in this instance as I only want the packs from the first of the result.
OrderBy()afterFirstOrDefault()doesn't make too much sense - this is an odd one for sure.SelectManydoesn't return anIOrderedEnumerablelikeOrderBydoes, so it would need to be after theSelectManycall.