title: Sorting Collection of One-To-Many relationship - Entity Framework Codefirst
body: <p>I have a codefirst entity model which has two entities, City and Locality. City has one to many relation with Locality. Here is how they are related.</p>
  
  <pre><code>public class City {
      public virtual List&lt;Locality&gt; Localities { get; set; }
  }
  
  public class Locality {
      public virtual City City { get; set; }
  }
  </code></pre>
  
  <p>Now I have some code which finds a particular City and loads Localities for that city too. I was looking to sort the loaded Localities by "Name" using LINQ IQueryable something like this</p>
  
  <pre><code>city = context.Cities.AsNoTracking().Include(c =&gt; c.Localities.OrderBy(l =&gt; l.Name))
                                      .Where(c =&gt; c.Id == id).FirstOrDefault();
  </code></pre>
  
  <p>When I use the above code it throws "ArgumentException". So I tried the code shown below.</p>
  
  <pre><code>city = context.Cities.AsNoTracking().Include(c =&gt; c.Localities)
                                      .Where(c =&gt; c.Id == id).FirstOrDefault();
  if (city != null) {
       city.Localities.OrderBy(l =&gt; l.Name);
  }
  </code></pre>
  
  <p>The above code does not throw any exceptions but it doesn't sort the the Localities by Name. I get Localities sorted by Id instead. </p>
  
  <p>Any ideas how to sort the "many side" of One-to-Many relationship</p>