0

lets say I have a Person class which contains list of child.

Not I would like to query database to get list of person with child inlcuded:

return context.Person.Include(p => p.Children);

Ok now I would like to modify that query so as a result I get list of Person but with only one child (lets say the oldest one sort by age desc)

Is it possible?

Thanks in advance

Snorlax
  • 787
  • 2
  • 9
  • 22
  • Check this answer http://stackoverflow.com/a/16501677/2224701, but do not expect to have that one chlild available via `person.Children` collection, it will be `new {person, child}`. – Vojtěch Dohnal Feb 22 '16 at 12:50

2 Answers2

2

What you describe could be achieved by a query like this:

from p in Persons
from ch in p.Children.OrderByDescending(x => x.Age).Take(1)
select new { p,ch }

Instead of Take(1) you can also use FirstOrDefault(): the resultset would then include also persons with no children:

from p in Persons
select new { p, p.Children.OrderByDescending(x => x.Age).FirstOrDefault() }

However the collection Children of a Person class is maintained automatically as a collection of all the Children of 1 Person instance and this meaning cannot be changed.

So as far as I know it is not possible, you need to create a new class containing that 1 Person + that 1 instance of Child.

Vojtěch Dohnal
  • 7,867
  • 3
  • 43
  • 105
0

I created a library for some cases like this.

https://github.com/deyunote/EntityFramework.Include

Using this library, you can describe as below

context.Person.Include(p => p.Children,
                       p => p.Children.OrderByDescending(x => x.Age).Take(1).ToList())
              .ToListWithInclude(); //Async:ToListWithAsync()
deyu
  • 329
  • 2
  • 6