我已经能够以编程方式将外部(即 BDC)查找字段添加到列表中,并且我还能够将相关的外部查找字段添加到同一列表中。我无法弄清楚的是如何以编程方式将依赖的外部查找字段添加到列表的默认视图中。
MSDN 上的这篇文章提供了一个如何向 SPView 添加常规依赖查找字段的示例 - 但我还没有找到一个示例来说明如何以编程方式将依赖外部查找字段添加到 SPView。
下面是我的 EventReceiver 的 FeatureActivated 方法中的代码,我使用它来将依赖的外部查找字段添加到我的 SharePoint 列表中,并尝试将该字段添加到列表的默认视图中。
var web = ((SPSite)properties.Feature.Parent).RootWeb;
var list = web.Lists.TryGetList("MyList");
var fldName = "EmployeeID";
var fld = list.Fields.CreateNewField("BusinessData", fldName) as SPBusinessDataField;
fld.SystemInstanceName = lobSystemInstanceName;
fld.EntityNamespace = entityNamespace;
fld.EntityName = entityName;
fld.BdcFieldName = entityFieldName;
//The dictionary object defined below contains key/value pairs that represent the
//field name as a string along with a boolean flag that specifies whether or not
//the secondary field should be added to the default view.
var secondaryFieldNames = new Dictionary<string, bool>()
{
{"FirstName", true},
{"LastName", true},
{"Title", false}
}
fld.SetSecondaryFieldsNames(secondaryFieldNames.Select(e => e.Key).ToArray());
var view = list.Views.DefaultView;
foreach (var secFld in secondaryFieldNames)
{
var viewFieldName = String.Format("{0}: {1}", fldName, secFld.Key);
if (!view.ViewFields.Exists(viewFieldName) && secFld.Value)
{
view.ViewFields.Add(viewFieldName);
view.Update();
}
}
如前所述,主查找字段和所有辅助查找字段都已成功添加到列表中。主要查阅字段已成功添加到列表的默认视图中。次要字段不是。