说明如何使用 Microsoft.Graph 客户端更新(修补)对象

Clarification on how to update (patch) objects using the Microsoft.Graph Client

以下代码是迄今为止我发现使用 Microsoft Graph Client Library

更新对象的唯一方法

场景:

  1. 加载现有对象(组织)
  2. 修改一个值(在 securityComplianceNotificationPhones 中添加条目)
  3. 发送更新

代码

var client = new GraphServiceClient(...);

var org = client.Organization["orgid"].Request().GetAsync().Result;
var secPhones = new List<string>(org.SecurityComplianceNotificationPhones);
secPhones.Add("12345");

var patchOrg = new Organization();
patchOrg.SecurityComplianceNotificationPhones = secPhones;

var orgReq = new OrganizationRequest(
     client.Organization[org.Id].Request().RequestUrl,
     client, new Option[] {});
orgReq.UpdateAsync(patchOrg).Wait();

由于两件事,我需要使用 patchOrg 实例:

  1. Graph API documentation 状态

    "In the request body, supply the values for relevant fields that should be updated. Existing properties that are not included in the request body will maintain their previous values or be recalculated based on changes to other property values. For best performance you shouldn't include existing values that haven't changed."

  2. 如果您实际上包含未更改的现有值 (即 assginedLicenses)请求失败,如果这些现有值 是只读的。

我的问题是:Is/will 有更直接的方法来更新现有对象,例如 Azure ActiveDirectory GraphClient?只是为了比较,Azure Active Directory Graph

中的相同场景
var client = new ActiveDirectoryClient(...);
var org = client.TenantDetails.GetByObjectId("orgid").ExecuteAsync().Result;
org.SecurityComplianceNotificationPhones.Add("12345");
org.UpdateAsync().Wait();

Graph 客户端库模型与您链接的 AAD 客户端库的旧版 SDK 模型略有不同。旧模型传递试图变得更聪明的对象并推断哪些属性已更改,只发送那些。该模型的主要缺点之一是该库在后台进行了更多的服务调用,并且每次调用的负载都更重,因为 ExecuteAsync() 通常需要检索请求构建器链中的每个对象。较新的库确实要求开发人员对正在传递的数据进行更明确的推理,但也可以更好地控制网络调用和有效负载。每个模型都有其权衡。

为了完成你想要的,这里是我推荐的方法,而不是完全创建第二个 org 对象:

var client = new GraphServiceClient(...);

var orgRequest = client.Organization["orgid"].Request();
var org = orgRequest.Select("securityComplianceNotificationPhones").GetAsync().Result;

var secPhones = new List<string>(org.SecurityComplianceNotificationPhones);
secPhones.Add("12345");

org.SecurityComplianceNotificationPhones = secPhones;

orgRequest.UpdateAsync(org).Wait();