开发者

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开发者_JAVA技巧 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


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜