Search code examples
c#linqincludesql-order-by

C# linq Include OrderBy


I need some help sorting data by Included data. In the example below, I am returning a purchase order where I want to sort the purchase order line items by the line item id.

return await context.PurchaseOrders
            .Where(x => x.PurchaseOrderNumber == PurchaseOrderNumber)
            .Include(x => x.PurchaseOrderLineItems.OrderBy(x => x.LineItemId))
            .ProjectTo<PurchaseOrderDetailDto>(mapper.ConfigurationProvider)
            .SingleOrDefaultAsync();

The data returned looks like this

{
    "purchaseOrderId": 1,
    "purchaseOrderNumber": 10776,
    "supplierNumber": "86087319",
    "supplierName": "SANOFI AVENTIS HEALTHCARE PTY LTD",
    "storeNumber": 101,
    "departmentId": 10,
    "orderDate": "2019-02-27",
    "deliverBy": "2019-03-13",
    "created": "2024-07-08T08:17:28.0300376",
    "orderTotal": 123748.02,
    "orderStatus": "Open",
    "receivedStatus": null,
    "purchaseOrderLineItems": [
        {
            "lineItemId": 10,
            "purchaseOrderId": 1,
            "productId": "CW_2477705",
            "productDescription": "Essentials Barrier Cream 300g Jar",
            "uom": "Each",
            "quantity": 204,
            "unitPrice": 6.63,
            "lineTotal": 1352.52,
            "gstPercentage": 10.0,
        },
        {
            "lineItemId": 8,
            "purchaseOrderId": 1,
            "productId": "CW_2478048",
            "productDescription": "Essentials Barrier Cream 75g Tube",
            "uom": "Each",
            "quantity": 240,
            "unitPrice": 3.35,
            "lineTotal": 804.0,
            "gstPercentage": 10.0,
         },
        {
            "lineItemId": 16,
            "purchaseOrderId": 1,
            "productId": "CW_2480590",
            "productDescription": "Selsun Blue Replenishing Anti Dandruff Shampoo",
            "uom": "Each",
            "quantity": 2160,
            "unitPrice": 4.63,
            "lineTotal": 10000.8,
            "gstPercentage": 10.0,
        }
    ]
}

The OrderBy on the following line doesn't appear to be working

.Include(x => x.PurchaseOrderLineItems.OrderBy(x => x.LineItemId))

Any ideas on how I can solve this? Thanks for your help.


Solution

  • You can do like this.

    var purchaseOrders = await context.PurchaseOrders
                .Where(x => x.PurchaseOrderNumber == PurchaseOrderNumber)
                .Include(x => x.PurchaseOrderLineItems)
                .ProjectTo<PurchaseOrderDetailDto>(mapper.ConfigurationProvider)
                .SingleOrDefaultAsync();
    
    purchaseOrders.PurchaseOrderLineItems = purchaseOrders.PurchaseOrderLineItems.OrderBy(x => x.LineItemId).ToList(); 
    
    return purchaseOrders;