LINQ “.Include” orderby in subquery

后端 未结 3 1618
天命终不由人
天命终不由人 2021-01-12 07:33

I have the following entity code, which returns all users and \"includes\" all of their sample requests:

    var userQuery = from u in _IntranetContext.UserS         


        
相关标签:
3条回答
  • 2021-01-12 08:12

    Edit: Treed by <15 seconds.

    var userQuery = from u in _IntranetContext.UserSet.Include("SampleRequests")
                    orderby u.LastName ascending, u.SampleRequestId descending
                    select u;
    
    0 讨论(0)
  • 2021-01-12 08:24

    Just add another ordering parameter to the orderby:

    var userQuery = from u in _IntranetContext.UserSet.Include("SampleRequests")
                               orderby u.LastName ascending, 
                                       u.SampleRequestId descending
                               select u;
    
    0 讨论(0)
  • 2021-01-12 08:29

    I can currently think of two options for what you want. You can select them into a new class, where the user and the associated requests are properties:

    var userQuery = from u in _IntranetContext.UserSet.Include("SampleRequests")
                    orderby u.LastName ascending
                    select new
                    {
                        User = u,
                        SampleRequests = u.SampleRequests.OrderByDescending(r => r.SampleRequestId)
                    };
    

    This will cause issues if you wanted to return this type, as it is anonymous.

    You can also select this into a new user object, similar to this:

    var userQuery = from u in _IntranetContext.UserSet.Include("SampleRequests")
                    orderby u.LastName ascending
                    select new User
                    {
                        Property1 = u.Property1,
                        Property2 = u.Property2,
                        Property3 = u.Property3,
                        SampleRequests = u.SampleRequests.OrderByDescending(r => r.SampleRequestId).ToList()
                    };
    

    This will return a collection of User objects, but updating the objects in the database could cause issues.

    0 讨论(0)
提交回复
热议问题