Programmatically Create Relation between lists in Sharepoint 2010

In this we will create two lists in SharePoint 2010 and setup the Relation between the lists by adding the lookup column. Please note that the belwo example is a console application.

string lookupFieldName = “RelatedField”;

using (SPSite site = new SPSite(“http://SpSite”))
{
using (SPWeb web = site.OpenWeb())
{
SPListCollection lists = web.Lists;
//Creating Parent list
Guid SourceListId = lists.Add(“Parent List”,”", SPListTemplateType.GenericList);
Console.WriteLine(“Parent List Done…”);

//Creating Child List
Guid TargetListId = lists.Add(“Child List”,”"
,SPListTemplateType.GenericList);
Console.WriteLine(“Child List Done…”);

SPList SourceList = lists[SourceListId];
SPList TargetList = lists[TargetListId];

SPFieldCollection Fields = TargetList.Fields;
//Adding a lookup Field in Child List
Fields.AddLookup(lookupFieldName, SourceList.ID, true);
Console.WriteLine(“Lookup Field Created”);

//Adding the Restrict behaviour
SPFieldLookup NewLookupField = Fields[lookupFieldName] as SPFieldLookup;
NewLookupField.Indexed = true;
NewLookupField.LookupField = “Title”;
NewLookupField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Restrict;
NewLookupField.Update();
Console.WriteLine(“Lookup field integrity enforced”);

//Adding Items in the List
SPListItem NewSourceItem = SourceList.Items.Add();
NewSourceItem["Title"] = “Parent Data”;
NewSourceItem.Update();
Console.WriteLine(“Source listitem created”);

SPListItem NewTargetItem = TargetList.Items.Add();
NewTargetItem["Title"] = “Child Data”;
NewTargetItem[lookupFieldName] = new SPFieldLookupValue(1, “Source Data”);
NewTargetItem.Update();
Console.WriteLine(“Parent listitem created”);
TargetList.Update();
SourceList.Update();
}
}