How to restrict deletions on Lookup field in SharePoint 2010


In this article we will be seeing how to restrict deletions on Lookup field in SharePoint 2010 using C# and power shell.

When you create a lookup column in SharePoint 2010 you can see "Relationship" where you can maintain referential integrity enforcing the relationships defined by lookup columns. Just like foreign key constraints in a relational database, in SharePoint 2010 you can configure restrict delete and cascade delete rules on lookup column relationships:

  • Cascade delete rules: Delete items that reference a record when you delete that record.
  • Restrict delete rules: Will prevent you from deleting a record that is referenced by a lookup column in another list.

Using C#:

  • Open Visual Studio 2010.
  • Create Console Application.
  • Replace the code with the following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace RestrictDeletions
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://serverName:1111/SitePages/Home.aspx"))
            {
                using (SPWeb web = site.RootWeb)
                {
                    SPList list = web.Lists.TryGetList("ChildList");
                    SPField field=list.Fields["Department"];
                    SPFieldLookup fieldLookup = (SPFieldLookup)field;
                    fieldLookup.Indexed = true;
                    fieldLookup.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Cascade;
                    fieldLookup.Update();
                }
            }
        }
    }
}

  • Hit F5.

Using PowerShell:

$siteURL="http://serverName:1111/"
$site=Get-SPSite $siteURL
$web=$site.Rootweb
$list=$web.Lists.TryGetList("ChildList")
$field=$list.Fields["Department"]
$fieldLookup=[Microsoft.SharePoint.SPFieldLookup]$field
$fieldLookup.Indexed=$true
$fieldLookup.RelationshipDeleteBehavior=[Microsoft.SharePoint.SPRelationshipDeleteBehavior]::Cascade
$fieldLookup.Update()
 

Up Next
    Ebook Download
    View all
    Learn
    View all