'check if graph.user manager exists without try catch

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?



Solution 1:[1]

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();

enter image description here

Solution 2:[2]

Get the user, not the manager. The user has a manager field which can be checked for null.

You still need to do try/catch in the case that the user is not a part of the org anymore or if the server has an internal error. 4xx and 5xx error responses throw exceptions in .NET code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tiny Wang
Solution 2 Matt Small