代码段:使用管理对象模型创建外部内容类型

上次修改时间: 2010年5月7日

适用范围: SharePoint Server 2010

本文内容
说明
先决条件
使用此示例

说明

以下代码示例演示如何通过使用服务器上的 BDC 管理对象模型,以编程方式创建外部内容类型。

备注

可以使用 BDC 管理客户端对象模型以类似的方式在客户端上创建外部内容类型。

先决条件

  • Microsoft SharePoint Server 2010 或 Microsoft SharePoint Foundation 2010 位于服务器上。

  • Microsoft .NET Framework 3.5 位于客户端计算机上。

  • Microsoft Visual Studio。

使用此示例

  1. 启动 Visual Studio 并创建 C# 控制台应用程序项目。创建项目时选择".NET Framework 3.5"。

  2. 从"视图"菜单中,单击"属性页"以显示项目属性。

  3. 在"生成"选项卡中,为"目标平台"选择"任何 CPU"。

  4. 关闭项目属性窗口。

  5. 在"解决方案资源管理器"中的"引用"下,删除除 System 和 System.Core 之外的所有项目引用。

  6. 向项目中添加以下引用:

    1. Microsoft.BusinessData

    2. Microsoft.SharePoint

    3. System.Web

  7. 用此过程结尾处列出的代码替换 Program.cs 中自动生成的代码。

  8. 将 <siteUrl> 字符串值替换为有效的 SharePoint 网站名称。另外,为每个外部系统设置 LobSystemInstance 参数。

  9. 保存该项目。

  10. 编译并运行该项目。

using System;
using System.Linq;
using Microsoft.BusinessData.MetadataModel;
using Microsoft.BusinessData.Runtime;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.SharePoint.BusinessData.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;


namespace Microsoft.SDK.SharePoint.Samples.Bdc.CreateEntity
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the Catalog for the SharePoint site
            BdcService service =
                SPFarm.Local.Services.GetValue<BdcService>(String.Empty);
            SPSite site = new SPSite("<siteUrl>");
            SPServiceContext context = SPServiceContext.GetContext(site);
            AdministrationMetadataCatalog catalog = 
                service.GetAdministrationMetadataCatalog(context);


            // Create a new Contact Model
            // NOTE: Assume that the "ContactModel" Model 
            // does not already exist.
            Model contactModel = Model.Create(
                "ContactModel", true, catalog);


            // Make a new Contact LobSystem
            // NOTE: Assume that the "AdventureWorks" LobSystem 
            // does not already exist.
            LobSystem adventureWorksLobSystem = 
                contactModel.OwnedReferencedLobSystems.Create(
                "AdventureWorks", true, SystemType.Database);

            // Make a new AdventureWorks LobSystemInstance.
            LobSystemInstance adventureWorksLobSystemInstance = 
                adventureWorksLobSystem.LobSystemInstances.Create(
                "AdventureWorks", true);

            // Set the connection properties.
            adventureWorksLobSystemInstance.Properties.Add(
                "AuthenticationMode", "PassThrough");
            adventureWorksLobSystemInstance.Properties.Add(
                "DatabaseAccessProvider", "SqlServer");
            adventureWorksLobSystemInstance.Properties.Add(
                "RdbConnection Data Source", "MSS2010");
            adventureWorksLobSystemInstance.Properties.Add(
                "RdbConnection Initial Catalog", "AdventureWorks");
            adventureWorksLobSystemInstance.Properties.Add(
                "RdbConnection Integrated Security", "SSPI");
            adventureWorksLobSystemInstance.Properties.Add(
                "RdbConnection Pooling", "true");

            // Create a new Contact Entity.
            Entity contactEntity = Entity.Create(
                "Contact", 
                "AdventureWorks", 
                true, 
                new Version("1.0.0.0"), 
                10000, 
                CacheUsage.Default, 
                adventureWorksLobSystem, 
                contactModel, 
                catalog);

            // Set the identifier to the ContactID column.
            contactEntity.Identifiers.Create(
                "ContactID", true, "System.Int32");

            // Create the Finder Method, 
            // i.e. the method to return all rows.
            CreateReadListMethod(catalog, contactEntity);

            // Create the Specific Finder Method, 
            // i.e. the method to return one row.
            CreateReadItemMethod(catalog, contactEntity);

            // Validate the Contact Entity.
            ActivationError[] activationErrors = 
                contactEntity.Validate();

            // Check if the validation failed.
            if (activationErrors.Count() == 0)
            {
                // The validation was successful so publish the Contact Entity.
                contactEntity.Activate();

                Console.WriteLine("Created Contact Model");
            }
            else
            {
                // The validation failed so display the validation errors.
                Console.WriteLine("Contact Model was not created and" + 
                    " failed with the following errors:");
                foreach (ActivationError item in activationErrors)
                {
                    Console.WriteLine(item.ToString());
                }

            }

            // Wait for any key to be hit before exiting the program
            Console.ReadKey();
        }
    
        private static void CreateReadListMethod(
            AdministrationMetadataCatalog catalog, Entity contactEntity)
        {
            // Create the Finder method
            Method getContactsMethod = contactEntity.Methods.Create(
                "GetContacts", true, false, "Contact");

            // Specify the query
            getContactsMethod.Properties.Add(
                "RdbCommandText", 
                "SELECT TOP(@MaxRowsReturned) [ContactID], [LastName]," + 
                " [Phone], [EmailAddress] FROM [Person].[Contact]");

            // Set the command type
            getContactsMethod.Properties.Add("RdbCommandType", "Text");

            // Set the additional property values so that this 
            // External Content Type can be displayed 
            // in SharePoint Designer.
            getContactsMethod.Properties.Add(
                "Schema", "Person");
            getContactsMethod.Properties.Add(
                "BackEndObjectType", "SqlServerTable");
            getContactsMethod.Properties.Add(
                "BackEndObject", "Contact");

            // Create a Filter so that we can limit the number 
            // of rows returned;
            // otherwise we may exceed the list query size threshold.
            FilterDescriptor limitRowsReturnedFilter = 
                getContactsMethod.FilterDescriptors.Create(
                "RowsReturnedLimit", true, FilterType.Limit, null);
            limitRowsReturnedFilter.Properties.Add(
                "IsDefault", true);

            // Create the RowsToRetrieve input parameter.
            Parameter maxRowsReturnedParameter = 
                getContactsMethod.Parameters.Create(
                "@MaxRowsReturned", true, DirectionType.In);

            // Create the TypeDescriptor for the MaxRowsReturned parameter.
            // using the Filter we have created.
            TypeDescriptor maxRowsReturnedTypeDescriptor = 
                maxRowsReturnedParameter.CreateRootTypeDescriptor(
                "MaxRowsReturned", 
                true, 
                "System.Int64", 
                "MaxRowsReturned", 
                null, 
                limitRowsReturnedFilter, 
                TypeDescriptorFlags.None, 
                null, 
                catalog);

            // Create the Contacts return parameter.
            Parameter contactsParameter = 
                getContactsMethod.Parameters.Create(
                "GetContacts", true, DirectionType.Return);

            // Create the TypeDescriptors for the Contacts return parameter.
            TypeDescriptor returnRootCollectionTypeDescriptor = 
                contactsParameter.CreateRootTypeDescriptor(
                "Contacts", 
                true, 
                "System.Data.IDataReader, System.Data, Version=2.0.0.0," + 
                " Culture=neutral, PublicKeyToken=b77a5c561934e089", 
                "Contacts", 
                null, 
                null, 
                TypeDescriptorFlags.IsCollection, 
                null, 
                catalog);
            TypeDescriptor returnRootElementTypeDescriptor = 
                returnRootCollectionTypeDescriptor.ChildTypeDescriptors.Create(
                "Contact", 
                true, 
                "System.Data.IDataRecord, System.Data, Version=2.0.0.0," + 
                " Culture=neutral, PublicKeyToken=b77a5c561934e089", 
                "Contact", 
                null, 
                null, 
                TypeDescriptorFlags.None, 
                null);
            returnRootElementTypeDescriptor.ChildTypeDescriptors.Create(
                "ContactID", 
                true, 
                "System.Int32", 
                "ContactID", 
                new IdentifierReference("ContactID", 
                    new EntityReference("AdventureWorks", "Contact", catalog), 
                    catalog), 
                null, 
                TypeDescriptorFlags.None, 
                null);
            returnRootElementTypeDescriptor.ChildTypeDescriptors.Create(
                "LastName", 
                true, 
                "System.String", 
                "LastName", 
                null, 
                null, 
                TypeDescriptorFlags.None, 
                null);
            returnRootElementTypeDescriptor.ChildTypeDescriptors.Create(
                "Phone", 
                true, 
                "System.String", 
                "Phone", 
                null, 
                null, 
                TypeDescriptorFlags.None, 
                null);
            returnRootElementTypeDescriptor.ChildTypeDescriptors.Create(
                "EmailAddress", 
                true, 
                "System.String", 
                "EmailAddress", 
                null, 
                null, 
                TypeDescriptorFlags.None, 
                null);

            // Create the finder method instance
            MethodInstance readListMethodInstance = 
                getContactsMethod.MethodInstances.Create(
                "GetContacts", 
                true, 
                returnRootCollectionTypeDescriptor, 
                MethodInstanceType.Finder, 
                true);

            // Set the default value for the number of rows 
            // to be returned filter.
            // NOTE: The method instance needs to be created first 
            // before we can set the default value.
            maxRowsReturnedTypeDescriptor.SetDefaultValue(
                readListMethodInstance.Id, Int64.Parse("200"));
        }

        private static void CreateReadItemMethod(
            AdministrationMetadataCatalog catalog, Entity contactEntity)
        {
            // Create the specific finder method
            Method getContactMethod = contactEntity.Methods.Create(
                "GetContact", true, false, "Contact");

            // Specify the query
            getContactMethod.Properties.Add(
                "RdbCommandText", 
                "SELECT [ContactID], [LastName], [EmailAddress]," + 
                " [Phone] FROM [Person].[Contact]" + 
                " WHERE [ContactID] = @ContactID");

            // Set the command type
            getContactMethod.Properties.Add("RdbCommandType", "Text");


            getContactMethod.Properties.Add(
                "Schema", "Person");
            getContactMethod.Properties.Add(
                "BackEndObjectType", "SqlServerTable");
            getContactMethod.Properties.Add(
                "BackEndObject", "Contact");

            // Create the ContactID input parameter
            Parameter contactIdParameter = 
                getContactMethod.Parameters.Create(
                "@ContactID", true, DirectionType.In);

            // Create the TypeDescriptor for the ContactID parameter
            contactIdParameter.CreateRootTypeDescriptor(
                "ContactID", 
                true, 
                "System.Int32", 
                "ContactID", 
                new IdentifierReference(
                    "ContactID", 
                    new EntityReference("AdventureWorks", "Contact", catalog), 
                    catalog), 
                null, 
                TypeDescriptorFlags.None, 
                null, 
                catalog);

            // Create the Contact return parameter
            Parameter contactParameter = 
                getContactMethod.Parameters.Create(
                "Contact", true, DirectionType.Return);

            // Create the TypeDescriptors for the Contact return parameter.
            TypeDescriptor returnRootCollectionTypeDescriptor = 
                contactParameter.CreateRootTypeDescriptor(
                "Contacts", 
                true, 
                "System.Data.IDataReader, System.Data, Version=2.0.0.0," + 
                " Culture=neutral, PublicKeyToken=b77a5c561934e089", 
                "Contacts", 
                null, 
                null, 
                TypeDescriptorFlags.IsCollection, 
                null, 
                catalog);            
            TypeDescriptor returnRootElementTypeDescriptor = 
                returnRootCollectionTypeDescriptor.ChildTypeDescriptors.Create(
                "Contact", 
                true, 
                "System.Data.IDataRecord, System.Data, Version=2.0.0.0," + 
                " Culture=neutral, PublicKeyToken=b77a5c561934e089", 
                "Contact", 
                null, 
                null, 
                TypeDescriptorFlags.None, 
                null);            
            returnRootElementTypeDescriptor.ChildTypeDescriptors.Create(
                "ContactID", 
                true, 
                "System.Int32", 
                "ContactID", 
                new IdentifierReference("ContactID", 
                    new EntityReference("AdventureWorks", "Contact", catalog), 
                    catalog), 
                null, 
                TypeDescriptorFlags.None, 
                null);            
            returnRootElementTypeDescriptor.ChildTypeDescriptors.Create(
                "LastName", 
                true, 
                "System.String", 
                "LastName", 
                null, 
                null, 
                TypeDescriptorFlags.None, 
                null);           
            returnRootElementTypeDescriptor.ChildTypeDescriptors.Create(
                "Phone", 
                true, 
                "System.String", 
                "Phone", 
                null, 
                null, 
                TypeDescriptorFlags.None, 
                null);            
            returnRootElementTypeDescriptor.ChildTypeDescriptors.Create(
                "EmailAddress", 
                true, 
                "System.String", 
                "EmailAddress", 
                null, 
                null, 
                TypeDescriptorFlags.None, 
                null);

            // Create the specific finder method instance
            getContactMethod.MethodInstances.Create(
                "GetContact", 
                true, 
                returnRootElementTypeDescriptor, 
                MethodInstanceType.SpecificFinder, 
                true);
        }
    }
}

请参阅

引用

BdcService

Services

GetAdministrationMetadataCatalog(SPServiceContext)

AdministrationMetadataCatalog

Model

Create(String, Boolean, AdministrationMetadataCatalog)

OwnedReferencedLobSystems

LobSystem

LobSystemInstance

Entity

ActivationError

Method

FilterDescriptor

Parameter

TypeDescriptor

MethodInstance

IdentifierReference

EntityReference