Search code examples
entity-frameworklinq-to-entities

how to select specific number of child entities instead of all in entity framework 3.5?


i am wondering how can i select specific number of child objects instead of taking them all with include?

lets say i have object 'Group' and i need to select last ten students that joined the group.

When i use '.Include("Students"), EF includes all students. I was trying to use Take(10), but i am pretty new to EF and programming as well, so i couldn't figure it out. Any suggestions?

UPDATED:

ok, i have Group object already retrieved from db like this:

Group group = db.Groups.FirstOrDefault(x=>x.GroupId == id)

I know that i can add Include("Students") statement, but that would bring ALL students, and their number could be quite big whether i need only freshest 10 students. Can i do something like this: var groupWithStudents = group.Students.OrderByDescending(//...).Take(10);?

The problem with this is that Take<> no longer appears in intellisense. Is this clear enough? Thanks for responses


Solution

  • Couldn't make Gratzy's suggestion with conditional include work... and found the solution here: http://msdn.microsoft.com/en-us/library/bb896249.aspx

    Query would look like this:

    group.Students.Attach(group.Students
                               .CreateSourceQuery()
                               .OrderByDescending(x=>x.JoinDate)
                               .Take(10));
    

    This is exactly what i was looking for!

    Thanks for all responses anyway!