Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

entity framework 4 - LINQ Query - how sort and filter on eager fetch

How do I do a eager query of a parent child relationship that:

  1. filters a on child fields
  2. sorts on both parent and child
  3. return a List or Parents with the children pre-populated

If I try

from p in _context.Parents.Include("children")
join c in _context.childrenon p.Id equals c.ParentId 
where d.DeletedDate == null
orderby p.Name ascending, c.Name 
select p

Then I get the Parent object back but each Parent has NULL for children

if I try

from p in _context.Parents.Include("children")
orderby p.Name ascending
select p

The query returns all Parents and children but they are not filtered or sorted.

The result I want back is a IEnumerable<Parent> i.e.

Parent[0].name = "foo"
Parent[0].children = IEnumerable<Child>
Parent[1].name = "bar"
Parent[1].children = IEnumerable<Child>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no direct way of doing this, but you can use somewhat of a workaround - project the parent and children onto an annonymous object and then select and return the parent from the object.

See similar question: Linq To Entities - how to filter on child entities

In your case you will have something along the lines of:

var resultObjectList = _context.
                       Parents.
                       Where(p => p.DeletedDate == null).
                       OrderBy(p => p.Name).
                       Select(p => new
                                 {
                                     ParentItem = p,
                                     ChildItems = p.Children.OrderBy(c => c.Name)
                                 }).ToList();

List<Parent> resultingCollection = resultObjectList.Select(o => o.ParentItem).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...