Search code examples
c#entity-frameworklinq-to-entities

Linq to entities group join on multiple tables


I'm trying to perform a group join on multiple tables with one to many relations, using into instead of group by. But something is not right. I get duplicate records for each Role a user has.

from compUsr in Repository.All<CompanyUser>()
join usr in Repository.All<User>() on compUsr.UserId equals usr.Id
join usrRole in Repository.All<UserRole>() on usr.Id equals usrRole.UserId
join role in Repository.All<Role>() on usrRoles.RoleId equals role.Id into roles
    select new UserDTO()
    {
        Id = usr.Id,
        Email = usr.Email
        Roles = roles.Select(r => new RoleDTO()
        {
            Id = r.Id
        })
    }

If I remove the join on Role table, and place the into statement on UserRole, the grouping works like a charm, but UserRole is just a linking table, so the Role table is the one I'm interested in. Any ideas how to group this as simple as possible? Thanks!


Solution

  • from compUsr in Repository.All<CompanyUser>()
    join usr in Repository.All<User>() on compUsr.UserId equals usr.Id
    join usrRole in Repository.All<UserRole>() on usr.Id equals usrRole.UserId
    join role in Repository.All<Role>() on usrRoles.RoleId equals role.Id
    group new { usr, role } by usr into grp
                        select new
                        {
                            Id = grp.Key.Id,
                            Email = grp.Key.Email,
                            Roles = grp.Select(r => new RoleDTO()
                            {
                                Id = r.role.Id
                            })
                        };