1

So let's say you have this query:

var query = context.Cars.Include("Owner").Include("Parts").Where(c=>c.id == strID);   

It grabs one row from Cars, and also rows from the Owners and Parts tables. What if I wanted to order the Parts table by the Parts.PartName column?

I'm using EF4.

leppie
  • 115,091
  • 17
  • 196
  • 297
flying227
  • 1,231
  • 3
  • 22
  • 36

1 Answers1

0

If you want to do it using eager loading you don't have other choice than project your query to apply an order by to the related entities:

//In Linq to Entities you can project using an anonymous type or a custom class(also known as a DTO)
var cars= context.Cars
                 .Include("Owner")
                 .Include("Parts")
                 .Where(c=>c.id == strID)
                 .Select(c=>new {//Change this projection at your convinience
                                 Car=c, 
                                 Parts= c.Parts.OrderBy(p=>p.PartName), 
                                 Owner=c.Owner
                                });

If you were using a major version of EF (at least 4.1), you could use Explicit Loading as I show below:

var car= context.Cars.Include("Owner").FirstOrDefault(c=>c.id == strID);
context.Entry(car) 
       .Collection(b => b.Parts) 
       .Query() 
       .OrderBy(p => p.PartName) 
       .Load(); 
ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • Hmm, intellisense doesn't seem to like that second line (context.Entry...) "does not contain a definition for 'Entry' and no extention method 'Entry' – flying227 Apr 11 '16 at 14:49
  • Did you add `System.Data.Entity` namespace?Check this reference: https://msdn.microsoft.com/en-us/library/gg696238(v=vs.113).aspx – ocuenca Apr 11 '16 at 14:51
  • oh, that's the thing, let me see if I can re adapt my answer because it only works since 4.1 version. Check this other [link](http://stackoverflow.com/questions/7113434/where-is-context-entry) for more info – ocuenca Apr 11 '16 at 15:20