Search code examples
c#.netentity-frameworkmany-to-manycode-first

Lambda Expression for Many to Many relationship


Based on the following Data Model, I want to write a "method syntax" lambda query that gives me a collection of RoleGroupMaps for a specific CMRole (in CMRoles table) and UIResource (in UIResources table).

enter image description here

I read this and this but can't get what I need.


Solution

  • assume urId is id of specific UIResource and listOfCMRoleIds is list of specified CMRole

    context.UIResource.Where(x => x.ID == urId)
        .Join(context.UIResourceGroupMaps,
            x => x.ID, x => x.UIResourceID,
            (x, y) => y)
        .Join(context.UIResourceGroups,
            x => x.UIResourceGroupID, x => x.ID,
            (x, y) => y)
        .Join(context.RoleGroupMaps.Join(context.CMRoles.Where(x => listOfCMRolesIds.Contains(x.ID)),
                                       x => x.CMRoleID, x => x.ID,
                                       (x, y) => x),
            x => x.ID, x => x.UIResourceGroupID,
            (x, y) => y);