Question

I have a class structure which is used by Entity Framework (code-first);

public class Product
{
  public int Id { get; set; }
  public string Name { get; set; }

  public virtual ICollection<Image> Images { get; set; }
}

public class Image
{
  public int Id { get; set; }
  public int Order { get; set; }
}

The Image class has an Order field, which can essentially handle sorting. At some point in my application I write a line such as;

BindImages(product.Images);

What I would like is for the Images to be automatically sorted by the Order field when I request a product.Images, without me having to write product.Images.OrderBy(x => x.Order) everywhere.

Does anyone have any suggestions?

Was it helpful?

Solution

EF cannot do for you what you want. But you can do this. You can add to your type another property

public IEnumerable<Image> OrderedImages
{
   get{return Images.OrderBy(x => x.Order); }
}

and use it instead previous collection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top