1
votes

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?

1
Show your model classes (Movie and Cast) and I can complete my answer..Risto M
@RistoM I added entities, your answer does not work for my scenarioleo

1 Answers

2
votes

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());