TFS API - 如何获取工作项的父级

时间:2012-02-17 15:15:00

标签: c# tfs tfs2010 tfs-sdk

我的最终目标是递归地获取一个工作项的父项,直到层次结构中不再有父项。目前,还没有任何递归,我仍然在优化获取父工作项的方式。我想到了一种涉及查询的方法:

public WorkItem GetParentWorkItem(int id)
{
    StringBuilder queryString = new StringBuilder("SELECT [System.Id]" +    
                                                  " FROM WorkItemLinks " +
                                                  " WHERE [Source].[System.WorkItemType] = '" + TFS_TIMESHEET_WORK_ITEM_TYPE + "'"  +
                                                  " AND [Source].[System.TeamProject] = '" + TFS_TIMESHEET_PROJECT_KEY + "'" +
                                                  " AND [Source].[System.Id] = " + id 
                                                  );
    Query wiQuery = new Query(GetWorkItemStore, queryString.ToString());
    WorkItemLinkInfo[] wiTrees = wiQuery.RunLinkQuery();
    WorkItem wi = GetWorkItemStore.GetWorkItem(wiTrees[1].TargetId);

    return wi;
}

此方法的问题在于它获取所有链接的工作项,包括前任,后继,子和父。我知道wiTrees[1]是父工作项,因此我对索引进行了硬编码。

我找到了一种从工作项商店获取“父”WorkItemTypeEnd对象的方法:

WorkItemLinkTypeEnd linkTypEnd = GetWorkItemStore.WorkItemLinkTypes.LinkTypeEnds["Parent"];

我从哪里开始?

2 个答案:

答案 0 :(得分:12)

这适用于TFS 2013:

var parent_link = work_item.WorkItemLinks.Cast<WorkItemLink> ().FirstOrDefault (x => x.LinkTypeEnd.Name == "Parent");

WorkItem parent_work_item = null;
if (parent_link != null)
    parent_work_item = work_item_store.GetWorkItem (parent_link.TargetId);

答案 1 :(得分:7)

找到一个解决方案,如果有父项,则返回父WorkItem,否则返回null。

public WorkItem GetParentWorkItem(int id)
    {
        StringBuilder queryString = new StringBuilder("SELECT [System.Id]" +    
                                                      " FROM WorkItemLinks " +
                                                      " WHERE [Source].[System.WorkItemType] = '" + TFS_TIMESHEET_WORK_ITEM_TYPE + "'" +
                                                      " AND [Source].[System.TeamProject] = '" + TFS_TIMESHEET_PROJECT_KEY + "'" +
                                                      " AND [Source].[System.Id] = " + id 
                                                      );
        Query wiQuery = new Query(GetWorkItemStore, queryString.ToString());
        WorkItemLinkInfo[] wiTrees = wiQuery.RunLinkQuery();

        int parentLinkId = GetWorkItemStore.WorkItemLinkTypes.LinkTypeEnds["Parent"].Id;

        foreach (WorkItemLinkInfo linkInfo in wiTrees)
        {
            // -2 is the LinkTypeId for parent
            if (linkInfo.LinkTypeId == parentLinkId)
            {
                workItem = GetWorkItemStore.GetWorkItem(linkInfo.TargetId);
                break;
            }
            else
            {
                workItem = null;
            }
        }
        return workItem;
    }