0

I have entities similar to this:

public class Search
{
    public int ID { get; set; }
    public bool Complete { get; set; }
    public int Processed { get; set; }
    public virtual ICollection<PostCode> PostCodes { get; set; }
}
public class PostCode
{
    public int ID { get; set; }
    public string Value { get; set; }
}

I want to make sure that the PostCode collection is always ordered by its ID field when I load a Search entity.

Is there a way to set an order for nested collection when I load it?

There is many thousand postcodes so it is expensive process to iterate over whole list. In the below code am I iterating over every postcode twice or is this the right way to do it?

Search s = db.Searches.Include("PostCodes").FirstOrDefault(x => x.Complete == false);

s.PostCodes = s.PostCodes.OrderBy(x => x.ID).ToList();

I haven't profiled it but it feels like it's taking longer now.

Guerrilla
  • 9,785
  • 21
  • 79
  • 149
  • This [post](http://stackoverflow.com/questions/9938956/entity-framework-loading-child-collection-with-sort-order) might be of interest you. Seems like it has to be done in either a hacky way, or performing two queries against the database. – scheien Sep 06 '15 at 22:57
  • Thanks. So I can't lazy load if I use OrderBy so I guess there isn't much improvement to be had. – Guerrilla Sep 06 '15 at 23:04

0 Answers0