Enforce SharePoint 2010 list relationship behavior (programatically)

List relationship is a new concept in SharePoint 2010 which allows you to have one list have a lookup into another one and if delete is performed on the dependent items – you can either choose to perform cascade delete or restrict deletion.

To set this up using UI, you need to pick Main and Dependent list, then establish a lookup in your Dependent that will point to a field in Main list, and right away you will see the options similar to below:

list relationship

Now, if you`re like me … you will probably want to configure this setting through solution deployment and not ask your users to perform manual configuration. Here is how to do that:

Note: We`ll use SharePoint 2010 Blog template which has Posts and Comments making them two dependent lists. I want to delete all of the comments when user deletes posts (out of the box comments remain undeleted).

1. Copy Blog Template (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\SiteTemplates\Blog) to your Blank SharePoint solution in Visual Studio 2010.

2. Open Blog->Lists->Comments->Schema.xml

3. Find the following field definition and add the highlighted part to it:

<Field Name=”PostTitle” Type=”Lookup” Required=”TRUE” DisplayName=”$Resources:comments_schema_blgfld_posttitle;” List=”$Resources:core,lists_Folder;/$Resources:core,blogpost_Folder;” ShowField=”Title” ID=”{a131e489-d3d6-4f0c-a152-a3beb89f12be}” Indexed=”TRUE” RelationshipDeleteBehavior=”Cascade” Sealed=”TRUE” SourceID=”http://schemas.microsoft.com/sharepoint/v3″ StaticName=”PostTitle”>

Note that I also have Indexed=”TRUE” in my field definition, now this is because each column that will have relationship with other list`s field has to be indexed – to speed up underlying processing.

Example of Blog site template is a great pattern to follow when you need to define your own relationship between lists.

Here is some more on the field usage.

Enjoy!

This entry was posted in sharepoint, sharepoint 2010 and tagged , , , , . Bookmark the permalink.

Comments are closed.