Create External List in C#

There are many reasons why you may want to create an External List in C# programmatically, for example as part of a Feature activation event or some other automated process.

For this example I have created an External Content Type from the Products table in the AdventureWorks2000 database. We need to know a few properties of our External Content Type before we can begin. If you have used BCS Meta Man to create your ECT these values should be as follows:

LobSystemInstance – BCSMetaManInstance
EntityNamespace – BCSMetaMan
Entity – dbo_Product
SpecificFinder – GetSingledbo_ProductEntityByID

1, Open Visual Studio 2010 and create a new console application.

2, Add the following references to the project:

Microsoft.SharePoint.dll

3, Here’s the code you can paste into your console application to create

SPListDataSource ds = new SPListDataSource();
ds.SetProperty(SPListDataSource.BDCProperties.LobSystemInstance, “BCSMetaManInstance”);
ds.SetProperty(SPListDataSource.BDCProperties.EntityNamespace, “BCSMetaMan”);
ds.SetProperty(SPListDataSource.BDCProperties.Entity, “dbo_Product”);
ds.SetProperty(SPListDataSource.BDCProperties.SpecificFinder, “GetSingledbo_ProductEntityByID”);

using (SPSite site = new SPSite(“http://localhost”))
{
    using (SPWeb web = site.RootWeb)
    {
        web.Lists.Add(“Products”, “External Products List”, “Lists/Products”, ds);
    }
}

Now if you run your console application this code will step through and create an External List for you, hooking the dbo_Product External Content Type as the data source. It’s interesting to note a few old Business Data Catalog terms around here!

<nick/>