LINQ Query - how sort and filter on eager fetch

前端 未结 3 1699
粉色の甜心
粉色の甜心 2020-12-20 05:03

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 Par
相关标签:
3条回答
  • 2020-12-20 05:18

    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();
    
    0 讨论(0)
  • 2020-12-20 05:35

    The solution depends on what exactly you are trying to do.

    The first query gives the impression that you want to "flatten out" the results in objects, like this (pseudocode, I hope it's clear what I mean):

    { Parent1, Child1 }
    { Parent1, Child2 }
    { Parent1, Child3 }
    { Parent2, Child1 }
    

    In this case each result "row" would be an object having a Parent and a Child property, and you could sort by parent name and then by child name.

    The second query just returns the Parent objects and (you don't show it but I assume EF has been instructed to do that) each one has a Children collection. In this case you can only sort by parent name; if you want to sort each Parent's children, sort the Children collection on that object by itself.

    Which of the two do you want to do?

    Update

    OK, it seems you want the second one. I don't believe it can be done directly. You can just do it when you enumerate the results - since the Parents are already sorted, simply sort each one's children:

    var sortedChildren = parent.Children.OrderBy(c => c.Name);
    
    0 讨论(0)
  • prefetching child fields:

    using (BlogDataContext context = new BlogDataContext())
    {
        DataLoadOptions options = new DataLoadOptions();
        options.LoadWith<Blog>(c => c.Categories);
        options.LoadWith<Blog>(c => c.Title);
        context.LoadOptions = options;
        Blog blog = context.Blogs.Single<Blog>(c => c.BlogId == 1);
    }
    
    0 讨论(0)
提交回复
热议问题