Program.cs looks like the following.
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
Microsoft.SharePoint;
namespace
ProjectedFields
{
class
Program
{
static void
Main(string[] args)
{
using (SPSite
site = new
SPSite("http://serverName:22222/sites/test"))
{
using (SPWeb
web = site.RootWeb)
{
SPList lookupList =
web.Lists.TryGetList("Departments");
SPList list =
web.Lists.TryGetList("Employees");
if (lookupList !=
null && list !=
null)
{
// Create the lookup column.
string strPrimaryColumn = list.Fields.AddLookup("Department",
lookupList.ID, true);
SPFieldLookup primaryColumn = (SPFieldLookup)list.Fields.GetFieldByInternalName(strPrimaryColumn);
primaryColumn.LookupField = lookupList.Fields["Name"].InternalName;
primaryColumn.Indexed =
true;
primaryColumn.RelationshipDeleteBehavior =
SPRelationshipDeleteBehavior.Restrict;
primaryColumn.Update();
// Projected Field
string strProjectedCol = list.Fields.AddDependentLookup("LookUp:Manager",
primaryColumn.Id);
SPFieldLookup projectedCol = (SPFieldLookup)list.Fields.GetFieldByInternalName(strProjectedCol);
projectedCol.LookupField = lookupList.Fields["Manager"].InternalName;
projectedCol.Update();
// Add the columns to the "All Items" view
SPView view = list.Views["All Items"];
view.ViewFields.Add(primaryColumn);
view.ViewFields.Add(projectedCol);
view.Update();
}
}
}
}
}
}