创建taxonomy field之前我们首先来学习一下如果创建termSet,原因是我们所创建的taxonomy field需要关联到termSet。
简单介绍一下Taxonomy Term Store的层次结构:
TermStore
Group
TermSet
Term //Term可以继续创建Term
1、首先,我们需要new TaxonomySession对象,然后获取到TermStore
TaxonomySession session = new TaxonomySession(Site);//Site即为SPSite对象 TermStore termStore = session.TermStores[MetadataService];//MetadataService 即为SharePoint Managed Metadata Service name, 如果没有即需要创建一个Managed Metadata Service,具体如何创建这里不做介绍。
2、创建Group,创建Group之前我们需要check一下Group是否存在,我们可以简单的通过Linq语句来完成所需要的工作
Group group = termStore.Groups.Where(g => g.Name.Equals(groupName, StringComparison.OrdinalIgnoreCase)).Count() > 0 ? termStore.Groups[groupName] : termStore.CreateGroup(groupName);
3、创建TermSet,创建TermSet的时候可以指定TermSet的Lcid,我们可以通过如下2中方式获取
int lcid = termStore.DefaultLanguage;//推荐 //or int lcid = CultureInfo.CurrentCulture.LCID;//不推荐,原因是机器语言和SharePoint环境语言有可能不一致
TermSet rootTermSet = group.TermSets.Where(ts => ts.Name == termSetName).Count() > 0 ? group.TermSets[termSetName] : group.CreateTermSet(termSetName, Guid.NewGuid(), lcid);
4、创建Term
Term term = rootTermSet.Terms.Where(t => t.Name.Equals(termname, StringComparison.OrdinalIgnoreCase)).Count() > 0 ? rootTermSet.Terms[termname] : rootTermSet.CreateTerm(termname, lcid, Guid.NewGuid());
5、commit
termStore.CommitAll();
6、创建Taxonomy field
TaxonomyField taxonomyField = Site.RootWeb.Fields.CreateNewField("TaxonomyFieldType", "taxonomyFieldName") as TaxonomyField; taxonomyField.Description = "This is test for cnblogs."; taxonomyField.SspId = termStore.Id; taxonomyField.TermSetId = rootTermSet.Id;//taxonomy field binding to termSet taxonomyField.AllowMultipleValues = true; taxonomyField.Group = "Custom Columns";//taxonmy field default site column group Site.RootWeb.Fields.Add(taxonomyField); Site.RootWeb.Update();
7、测试,获取taxonomy field
TaxonomyField field = site.RootWeb.Fields["taxonomyFieldName"] as TaxonomyField;
OK,you have been created taxonomyField successfully。