如何在EF中订购实体的子集 [英] How to order child collections of entities in EF

查看:91
本文介绍了如何在EF中订购实体的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

public IEnumerable<Team> GetAllTeamsWithMembers(int ownerUserId)
        {
            return _ctx.Teams
                 .Include(x => x.TeamMembers)
                 .Where(x => x.UserId == ownerUserId)
                 .OrderBy(x => x.Name).ToList();

        }

我如何按照他们的名字订购团队,然后让每个团队的所有子成员按照他们的名字排序?

How do I go about ordering the teams by their name, and then have all the child members of each team sorted by their name?

似乎这样做需要创建一个新的DTO类并使用select。我想使用已经创建的EF实体,在这种情况下,Team有一个导航属性给Members。我从我的存储库层返回 IEnumerable< Team>

It seems that do this I need to create a new DTO class and use a select. I'd like to use the EF entities already created, in this case Team has a navigation property to Members. I return IEnumerable<Team> out from my repository layer.

似乎没有一种整齐的方法来排序EF中的子集。任何人都可以帮忙?

There doesn't seem to be a neat way of ordering child collections in EF. Can anyone help?

推荐答案

加载数据后,您可以加载数据并在内存中排序。

You could load the data and sort in memory after loading it.

IEnumerable<Team> teams = _ctx.Teams
            .Include(x => x.TeamMembers)
            .Include(x => x.TeamMembers.Select(u => u.User))
            .Where(x => x.UserId == ownerUserId)
            .OrderBy(x => x.Name).ToList();

foreach (var team in teams)
{
    team.TeamMembers = team.TeamMembers.OrderBy(m => m.Name);
    foreach (var teamMember in team.TeamMembers)
    {
        teamMember.Users = teamMember.Users.OrderBy(u => u.Name);
    }
}

或者您可以使用投影并使用更改跟踪EF排序您的收藏。 这是一个例子过滤包含但与订购相同的工作。

Or you could use Projections and use the Change Tracking of EF to sort your collection. Here is an example of filtering an Include but the same works for Ordering.

这篇关于如何在EF中订购实体的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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