简体   繁体   中英

Azure Active Directory Api - Add user To Group Fails

I'm trying to add user already exists on the azure active directory to a group already exists there too , via Azure AD Graph API:

IUser userToBeAdded1 = activeDirectoryClient.Users.Where(user => user.ObjectId == "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").ExecuteSingleAsync().Result;

            Group retrievedGroup = new Group();
            string searchString = "Development";
            List<IGroup> foundGroups = null;
            foundGroups = activeDirectoryClient.Groups.Where(group => group.DisplayName.StartsWith(searchString)).ExecuteAsync().Result.CurrentPage.ToList();

            if (foundGroups != null && foundGroups.Count > 0)
            {
                retrievedGroup = foundGroups.First() as Group;
                if (retrievedGroup.ObjectId != null)
                {
                    try
                    {
                        activeDirectoryClient.Context.AddLink(retrievedGroup, "members", userToBeAdded1);
                        activeDirectoryClient.Context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("\nError assigning member to group. {0} {1}",
                            ex.Message, ex.InnerException != null ? ex.InnerException.Message : "");
                    }
                }
            }

and each time i get the same error : "The context is not currently tracking the entity."

at this line :

activeDirectoryClient.Context.AddLink(retrievedGroup, "members", userToBeAdded1);

This issue is now fixed in the latest version of the Graph client library. Please see the answer here for details: Azure Active Directory Graph Client 2.0 - Context is not currently tracking the entity

Hope this helps,

Try this (not tested):

var userToBeAdded1 = activeDirectoryClient.Users
    .FirstOrDefaultAsync(user => user.ObjectId == "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");

var searchString = "Development";
var foundGroup = activeDirectoryClient.Groups
    .FirstOrDefaultAsync(group => group.DisplayName.StartsWith(searchString));

if (foundGroup != null && foundGroup.ObjectId != null)
{
    try
    {
        activeDirectoryClient.Context.AddLink(retrievedGroup, "members", userToBeAdded1);
        activeDirectoryClient.Context.SaveChanges();
    }
    catch (Exception ex)
    {
        Console.WriteLine("\nError assigning member to group. {0} {1}", ex.Message, ex.InnerException != null ? ex.InnerException.Message : "");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM