如何以编程方式 link Azure DevOps 中的分支和工作项

How to link a branch and work item in Azure DevOps programmatically

我正在尝试找到一种方法,通过我正在构建的应用程序 (Basically just this, but within a C# console app) 在 Azure DevOps 中将分支添加为 link。

我越来越熟悉 VisualStudio Services 和 TeamFoundation .NET 库,例如,我尝试使用已经通过 DevOps 创建的 link 之一获取工作项 UI 并将其移植到另一个工作项,如下所示:

var workItemWithBranchLink = await _WorkItemTrackingHttpClient.GetWorkItemAsync(3985, expand: WorkItemExpand.Relations);
var workItemWithoutBranchLink = await _WorkItemTrackingHttpClient.GetWorkItemAsync(3988, expand: WorkItemExpand.Relations);
var document = new JsonPatchDocument();
document.Add(new JsonPatchOperation()
{
    Operation = Operation.Add,
    Path = "/relations",
    Value = workItemWithBranchLink.Relations 
});
await _WorkItemTrackingHttpClient.UpdateWorkItemAsync(document, (int)workItemWithoutBranchLink.Id);

但是,这会引发异常

Microsoft.VisualStudio.Services.WebApi.Patch.PatchOperationFailedException: 'Work item patch does not support patching the top level property at path /relations.

由于 workItemWithoutBranchLink.Relations 为空,我不确定我还能如何修补它。

有什么想法吗?

尝试将您的路径更新为 "/relations/-"。我不确定 .net 库中的补丁格式是否遵循 Rest API 但似乎可能给出了顶级 属性 错误消息。即,如果您添加 /-,您将不再处于顶层。

好像也是这个samples library用的格式。

对于 git link 语法略有不同,这是一个工作示例(对于 link master 分支):

VssConnection testConnection = new VssConnection(new Uri("azure-devops-uri"), new Microsoft.VisualStudio.Services.Common.VssCredentials());
var workItemClient = testConnection.GetClient<WorkItemTrackingHttpClient>();
var gitClient = testConnection.GetClient<GitHttpClient>();
string projectId = "cf456145-abgd-ffs23-be61-0fca39681234";
string repositoryId = "d6856145-abgd-42a3-be61-0fca3968c555";
var branchUri = string.Format
(
    "vstfs:///Git/Ref/{0}%2f{1}%2f{2}",
    projectId,
    repositoryId,
    "GBmaster"
);

var json = new JsonPatchDocument();
json.Add(
new JsonPatchOperation()
{
     Operation = Operation.Add,
     Path = "/relations/-",
     Value = new
     {
            rel = "ArtifactLink",
            url = branchUri,
            attributes = new
            {
                name = "Branch",
                comment = "Comment"
            }
     }
});

try
{
     int workItemToUpdate = 142144;
     var update = workItemClient.UpdateWorkItemAsync(json, workItemToUpdate).Result;
}
catch (Exception e)
{
     var error = e.Message;
}