How to order child collections of entities in EF

后端 未结 3 1173
旧时难觅i
旧时难觅i 2020-12-05 13:17

I have the following query:

public IEnumerable GetAllTeamsWithMembers(int ownerUserId)
        {
            return _ctx.Teams
                 .         


        
3条回答
  •  生来不讨喜
    2020-12-05 13:51

    You could dump your teams and their team members into an anonymous type (probably not what you want), like this:

    public IEnumerable GetAllTeamsWithMembers(int ownerUserId)
    {
        return (from t in _ctx.Teams
            where t.UserId == ownerUserId
            select new {
                Team = t,
                TeamMembers = t.TeamMembers.OrderBy(m => m.Name)
            }).ToList()
    }
    

    You can then loop through them:

    foreach(Team team in GetAllTeamsWithMembers(1234))
    {
        string teamName = team.Team.Name;
        string firstTeamMemberName = team.TeamMembers.First().Name;
    }
    

    Update: For the record, my opinion is to not use this solution, but to sort each collection in a loop or during rendering/binding.

    I removed the 2nd solution, since it was pointed out that EF cannot select into entities.

提交回复
热议问题