In EF, how do you organise the child collections of entities?

entity-framework linq

Question

I need some information about:

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

        }

How can I arrange the teams according to their names and then arrange the young players on each team according to their names?

It seems that in order to do this, I must use a select and a new DTO class. In this situation, Team has a navigation attribute to Members, thus I'd want to leverage the EF entities that have already been constructed. I revertIEnumerable<Team> out of the layer of my repository.

In EF, there doesn't seem to be a tidy method to organise child collections. Can anyone assist?

1
30
12/9/2011 3:01:46 PM

Accepted Answer

The data might be loaded and then sorted in memory.

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

Alternately, you might organize your collection using Projections and EF's Change Tracking. filtering an Include, but the same principle also applies to ordering.

25
12/9/2011 3:08:24 PM

Popular Answer

You could enter your teams' members in an anonymous kind, but that's probably not what you want.

public IEnumerable<Team> 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()
}

Then, loop through them as follows:

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

Update: For the record, I think you should sort each collection in a loop or while rendering/binding instead of using this approach.

Since it was noted that EF cannot select inside entities, I eliminated the second solution.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow