使用户A公司管理员失败并显示错误 - Azure广告图

时间:2016-03-15 21:56:33

标签: azure azure-ad-graph-api

我有一个使用Azure Graph API创建用户的方法(用户成功创建),然后尝试将用户添加到公司管理员组,但是我收到此错误:

System.InvalidOperationException: The context is already tracking the entity.

Result StackTrace:  
at System.Data.Services.Client.EntityTracker.AddEntityDescriptor(EntityDescriptor descriptor)
   at System.Data.Services.Client.DataServiceContext.AddObject(String entitySetName, Object entity)
   at Microsoft.Azure.ActiveDirectory.GraphClient.DirectoryObjectCollection.AddDirectoryObjectAsync(IDirectoryObject item, Boolean deferredSave)

当我点击此行时出现错误:

await drrole.Members.AddDirectoryObjectAsync(usr as GraphClient.DirectoryObject);

这是函数的完整主体:

await client.Users.AddUserAsync(graphUser);

var directoryRoles = await client.DirectoryRoles.ExecuteAsync();
var companyAdminRole = directoryRoles.CurrentPage.FirstOrDefault(m => m.DisplayName == "Company Administrator");
if (companyAdminRole != null)
{
    var drrole = client.DirectoryRoles.GetByObjectId(companyAdminRole.ObjectId);
    var usr = await client.Users.GetByObjectId(graphUser.ObjectId).ExecuteAsync();
    await drrole.Members.AddDirectoryObjectAsync(usr as GraphClient.DirectoryObject);
}

我正在使用SDK的2.1.0版本: https://www.nuget.org/packages/Microsoft.Azure.ActiveDirectory.GraphClient/

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

 var directoryRoles = activeDirectoryClient.DirectoryRoles.ExecuteAsync();
        var companyAdminRole = directoryRoles.Result.CurrentPage.FirstOrDefault(m => m.DisplayName == "Company Administrator") as DirectoryRole;
        if (companyAdminRole != null)
        {
            var drrole = activeDirectoryClient.DirectoryRoles.GetByObjectId(companyAdminRole.ObjectId);
            var usr = activeDirectoryClient.Users.GetByObjectId(newUser.ObjectId).ExecuteAsync();
            ((DirectoryRole)companyAdminRole).Members.Add(usr.Result as DirectoryObject);
            companyAdminRole.UpdateAsync();
        }

this blog中所述,您可以使用将用户添加到组的相同结构将用户添加到DirectoryRole对象。
enter image description here

我写了一个样本并经过测试而没有遇到您的问题: enter image description here

希望这有帮助。