Today I was asked to build the Azure Function which removes existing link between work items from Azure DevOps. Azure DevOps documentation has an example about this method call, but the documentation itself is quite thin.
To delete only certain type of link we need to first load the work item from Azure DevOps and then try to find the index of link we want to delete. When loading work item from Azure DevOps, remember to set expand parameter into All mode, otherwise Relations property will be null:
var workItem = await workItemTrackingClient.GetWorkItemAsync(workItemId, expand: WorkItemExpand.All);
After loading work item we can access it’s links with Relations property. To get correct index of relation we can use List‘s FindIndex method. For example this code finds index of parent – child type of link:
var relations = workItem.Relations.ToList(); // Find correct relation which matches given link type var parentChildRelationIndex = relations.FindIndex(rel => string.Equals("System.LinkTypes.Hierarchy-Reverse", rel.Rel));
Now we know the index of relation which we want to remove. Next we can do the actual removing by creating JsonPatchDocument and passing it into work item tracking client
var deleteOperation = new JsonPatchOperation() { Operation = Microsoft.VisualStudio.Services.WebApi.Patch.Operation.Remove, Path = $"/relations/{parentChildRelationIndex}", }; var patchDocument = new JsonPatchDocument { releaseLinkOperation }; // Then the actual update for target work item (workItem.Id) await workItemTrackingClient.UpdateWorkItemAsync(patchDocument, workItem.Id.Value);
That’s it. Azure DevOps documentation contains list of work item relation types which can be used as link types.