Creating a linked Workitem via the TFS API

I have a customer that wanted to create Approvals for a particular work item type. We decided the best way to do this would be to create an Approval work item type and a new Link type called Approvals.

I found it difficult to find an example out there of creating new work item and linking it to another using my own link type. Once I got it working I thought I would Blog it so the next person looking for this has one more example.

Here are the steps; first using the process editor I created a new Link Type (see screen shot below for details). You can use the command line tool witadmin importlinktype to import your link type to the project.


Now to write a web service that is called via bissubscribe to create approvals for my source work item when the source work item is created. In the real code this was a bit more complicated. We had to look up who many approvals were required and create on approval for each person that was required. I have trimmed the code down to the bare necessities just to illustrate how to create the link.  

Therefore here is a sample of the code to create a new work item of the type Approval and link it to the source work item with the relationship Approved By.

//Get the TFS Collection and ensure Authenticated
TfsTeamProjectCollection TfsCollection = new TfsTeamProjectCollection(new Uri "https://Server/tfs/Collection"));
//Get the Work item store
WorkItemStore workItemStore = TfsCollection.GetService<WorkItemStore>();
//Get the project 
Project project = workItemStore.Projects["MyProject"];
//Get the Source Work item (Take for granted I have been passed the ID of the work item to be approved
WorkItem source = workItemStore.GetWorkItem(ID);
//Make a copy of that as an Approval. This way all the common data is pushed into the approval
WorkItem approval = source.Copy(project.WorkItemTypes["Approval"], WorkItemCopyFlags.None);
//Remove the related link that is created by the copy method
//Save the new work item

//Create a link of the type Approvals
WorkItemLinkType linkType = workItemStore.WorkItemLinkTypes["Approvals"];
//Create a linktypeend using the foward name in out case that is Approved By
WorkItemLinkTypeEnd linkTypeEnd = workItemStore.WorkItemLinkTypes.LinkTypeEnds[linkType.ForwardEnd.Name];
//Add the link to the source work item
source.Links.Add(new RelatedLink(linkTypeEnd, approval.Id));

Pingbacks and trackbacks (2)+