Sorting eager loaded Child Collections With Linq To SQL

By default Linq to SQL would lazy load all your child collections like when you have an instance of customer, its Orders are not loaded. ON traversing the Orders collection,  Linq to SQL fetches the Orders for that customer. You can use LoadWith operator to eagerly load the Orders for the customer. But what if you also want to sort that Order collection when your eagerly fetching the Orders. In that case you can use AssociateWith Method and specify the column that you want to order your Orders Collection by. Here is an example that accomplishes that.

image

image

In the above code, I am using LoadWith method which basically says that when you are retrieving the customer also retrieve its Orders as well. You can see from the output on the screen, when I traverse the Orders Collection, there is no additional query being sent to the database. Initial query retrieves both Customer and its orders. Further down I am making use of AssociateWith which sorts the orders by lowest freight. You an confirm from the output that we are printing all the Orders for ALFKI customer in ascending order of freight.

No Comments