I have all my Active Directory users in a list and am iterating through the users to get their manager, using the below code.
foreach (User u in userResult)
{
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var directoryObject = await graphClient2.Users[u.UserPrincipalName].Manager
.Request()
.GetAsync();
}
This works fine if the user has a manger, but if not, the code fails. The only way i can currently see around this is to use a try catch, but that feels crude, and when iterating over a lot of users, its not very efficient.
is there a better way of doing this?
You can use OData query expand parameter here to query manager alone with users.
Query url looks like this:
https://graph.microsoft.com/v1.0/users?$expand=manager($select=id,displayName)
And when using Graph SDK in asp.net core, since you need to query all users, you should use client credential flow, and it should look like this, please note, if the use doesn't have an manager, the property Manager
will be null:
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_clientid";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var users = await graphClient.Users.Request().Expand("manager($select=id,displayName)").GetAsync();