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
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.