leo
leo

Reputation: 455

Ordering Included Entity

I am using entity framework v2.2.3. I am trying to order a sub-entity by using the following code but it did not work.

var result= _databaseContext.Movie.AsNoTracking().Include(p => p.Cast.OrderByDescending(c => c.Birthday)).ToList();

Error:

The Include property lambda expression 'p => {from Cast c in p.Casts orderby [c].Birthday desc select [c]}' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

Entities:

public class Movie
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Cast> Casts { get; set; }
    }

  public class Cast
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
    }

Do you have any idea?

Upvotes: 1

Views: 69

Answers (1)

Risto M
Risto M

Reputation: 3009

There is no way to sort eager-loaded (.Include-queried) child collections as we have seen here and here.

You have to first load Movies and then sort their Casts-collections. Try this:

var result= _databaseContext.Movie.AsNoTracking().Include(p => p.Casts).ToList();

results.ForEach(x => x.Casts = x.Casts.OrderBy(y => y.BirthDay).ToList());

Upvotes: 2

Related Questions