MS Graph API C# Add user to group

Viewed 10579

I've been investigating how to add (and later remove) a user from an Azure AD group using the Microsoft Graph API (the dotnet/C# library available on nuget).

Nuget MS Graph API

Ignoring all else around getting a connected GraphServiceClient etc. I'm trying code very similar to the sample below, not getting any exception (suggesting things are fine) but when I get the group once again via the API, it's not got any members still!

Quickwatch of returned group object after modification attempt

Interestingly (as an aside), when I ask for memberOf property on the user object and tell it to expand it, it comes back null still.

var user = await client.Users[userPrincipalName]
             .Request()
               .Select("id,memberOf")
                 .Expand("memberOf")
                   .GetAsync();

var group = await client.Groups[groupId]
              .Request()
                .Select("members")
                  .Expand("members")
                    .GetAsync();

group.Members.Add(user);

await client.Groups[groupId].Request().UpdateAsync(group);

// userPrincipalName => "test.user@mytenant.com"
// groupId => the object GUID for the group

Does anyone know what I'm doing wrong here? The docs I used to come up with this code were based on the links to the following documents:

API doc for 'group'

Adding a member to a group

Also, I tried to style the approach on the solution suggested here to setting licenses for users:

Assign user license via Graph API

As usual, thanks for any help.

Peter

Additional

I've also tried poking around in the graph API looking at potentially updating the .Members property/resource rather than the group itself:

await client.Groups[groupId].Members.Request(). // <-- Only has GetAsync()

But it only has the GetAync() method available to it.

Updated based on answer

var usersGroups = await client.Users[userPrincipalName].MemberOf.Request().GetAsync();

if (!usersGroups.Any(g => g is Group && g.Id == groupId))
{
    // User is not a member of the group, add them.
    var user = await client.Users[userPrincipalName].Request().Select("id").GetAsync();
    await client.Groups[groupId].Members.References.Request().AddAsync(user);
}

I've added the code snippet above based on the answer, as I think it succinctly answers the issue regarding adding members.

Thanks to Nan Yu for the answer.

1 Answers
Related