views:

45

answers:

2

Hi all,

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

+3  A: 

I believe Take(10) would be correct.

 var Students= (from c in Groups
                orderby c.DateAdded descending
                select c).Take(10);

My experience with Take though is that it generates some awful sql.

EDIT:

see if this blog post helps, it talks of conditional includes.

http://blogs.msdn.com/b/alexj/archive/2009/10/13/tip-37-how-to-do-a-conditional-include.aspx

Gratzy
how can i add it to already selected Group? And what is better way than using Take(10)?
Sasha
"how can i add it to already selected Group?" I don't understand
Gratzy
He wants the loaded entities to be connected with the rest of the object graph. It's not the best solution but you can load the students with .Include("Groups"). Which means they are not really connected. But you can access the data of Groups.
DHN
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!
Sasha
+1  A: 

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!

Sasha
Glad you found a solution!
Gratzy