1

I want to retrieve an object plus its filtered/ordered collection property using EF 5. However, my current code throws an exception:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties

Here is the class of the object I want to retrieve:

public class EntryCollection
{
    [Key]
    public int Id { get; set; }
    public ICollection<Entry> Entries { get; set; }

    ...
}

And here is the definition of Entry:

public class Entry
{
    [Key]
    public int Id { get; set; }
    public DateTime Added { get; set; }

    ... 
}

I wanted to retrieve the EntryCollection which contains only the most recent entries, so here is the code I tried:

using (var db = new MyContext())
{
    return db.EntryCollections
             .Include(ec => ec.Entries.OrderByDescending(e => e.Added).Take(5))
             .SingleOrDefault(ec => ec.Foo == "bar');
}

Any ideas?

OJ Raqueño
  • 4,471
  • 2
  • 17
  • 30

1 Answers1

2

You cant use OrderBy inside an include.

what about the following

using (var db = new MyContext())
{
    return db.EntryCollections
             .Where(ec => ec.Foo == "bar")
             .Select(ec=> new Something{Entries = ec.Entries.OrderByDescending(e => e.Added).Take(5) }, /*some other properties*/)
             .SingleOrDefault();
}

or do it in two seperate queries

undefined
  • 33,537
  • 22
  • 129
  • 198
  • Hi, thanks for your answer. Can 'Something' be EntryCollection? When I tried that I got an exception: 'The entity or complex type 'MyNamespace.EntryCollection' cannot be constructed in a LINQ to Entities query.'. – OJ Raqueño Aug 11 '13 at 06:50
  • Looks like the answer to my previous comment can be found here: http://stackoverflow.com/questions/5325797/the-entity-cannot-be-constructed-in-a-linq-to-entities-query?rq=1 I might have to go with two queries on this one. – OJ Raqueño Aug 11 '13 at 06:55
  • I went with two separate queries. First to load the EntryCollection without the entries. Then another one to load the entries. – OJ Raqueño Aug 11 '13 at 07:03