LINQ".include"子查询中的orderby [英] LINQ ".Include" orderby in subquery

查看:302
本文介绍了LINQ".include"子查询中的orderby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下实体代码,该代码返回所有用户并包括"其所有示例请求:

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

    var userQuery = from u in _IntranetContext.UserSet.Include("SampleRequests")
                           orderby u.LastName ascending
                           select u;

每个用户都有多个SampleRequests.每个SampleRequest都有一个ID#(只是一个整数:1、22、341等).上面的LINQ to实体会像这样抓住用户及其SampleRequests:

Each user has multiple SampleRequests. Each SampleRequest has an ID# (just an integer: 1, 22, 341, etc). The above LINQ to entities grabs the users and their SampleRequests like so:

User1:33、22、341、12

User1: 33, 22, 341, 12

User2:24、3、981

User2: 24, 3, 981

如您所见,SampleRequest ID#不是按升序排列的.我希望结果井然有序.

As you can see the SampleRequest ID# are not in an ascending order. I would like the results to be in order.

如何将orderby约束放在包含的SampleRequests ID#

How do I put the orderby constraint on the Included SampleRequests ID#

请注意:SampleRequestId是SampleRequest的属性,而不是User对象的属性

Please note: SampleRequestId is a property of the SampleRequest...not a property of the User object

推荐答案

我目前可以想到两个您想要的选项.您可以将它们选择到新类中,其中用户和相关请求是属性:

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()
                };

这将返回User对象的集合,但是更新数据库中的对象可能会导致问题.

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

这篇关于LINQ".include"子查询中的orderby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆