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.
public class City {
public virtual List<Locality> Localities { get; set; }
}
public class Locality {
public virtual City City { get; set; }
}
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
city = context.Cities.AsNoTracking().Include(c => c.Localities.OrderBy(l => l.Name))
.Where(c => c.Id == id).FirstOrDefault();
When I use the above code it throws "ArgumentException". So I tried the code shown below.
city = context.Cities.AsNoTracking().Include(c => c.Localities)
.Where(c => c.Id == id).FirstOrDefault();
if (city != null) {
city.Localities.OrderBy(l => l.Name);
}
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.
Any ideas how to sort the "many side" of One-to-Many relationship