Поделиться через


Фрагмент кода: выполнение экземпляра метода Updater внешнего типа контента

Дата последнего изменения: 6 мая 2010 г.

Применимо к: SharePoint Server 2010

В этой статье
Описание
Необходимые компоненты
Использование этого примера

Описание

В следующем примере кода показано программное выполнение экземпляра метода Updater внешнего типа контента с помощью объектной модели среды выполнения BDC на сервере.

Необходимые компоненты

  • Microsoft SharePoint Server 2010 или Microsoft SharePoint Foundation 2010 на сервере.

  • Microsoft .NET Framework 3.5 на клиентском компьютере.

  • Microsoft Visual Studio.

  • По крайней мере один внешний тип контента зарегистрирован в хранилище метаданных BDC.

Использование этого примера

  1. Запустите Visual Studio и создайте проект консольного приложения C#. При создании проекта выберите .NET Framework 3.5.

  2. В меню Вид выберите Страницы свойств, чтобы вывести свойства проекта.

  3. На вкладке Построение в качестве Целевой платформы выберите Любой ЦП.

  4. Закройте окно свойств проекта

  5. В обозревателе решений в разделе Ссылки удалите все ссылки проекта кроме System и System.Core.

  6. Добавьте в проект следующие ссылки:

    1. Microsoft.BusinessData

    2. Microsoft.SharePoint

    3. System.Web

  7. Замените автоматически созданный код в файле Program.cs на код, приведенный в конце этой процедуры.

  8. Замените значения <siteUrl>, nameSpace> и <entityName> на допустимые.

  9. Сохраните проект.

  10. Скомпилируйте и запустите проект.

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

namespace SDKSamples
{
    class Methods
    {
        static void Main(string[] args)
        {
            BDCUpdate();
        }

        //How To: Edit an item from an External Content Type
        public static void BDCUpdate()
        {
            //Specify the SiteURL, Namespace and the Entity Name
            string SiteURL = "<siteUrl>";
            string nameSpace = "<nameSpace>";
            string entityName = "<entityName>";
           
            using (SPSite site = new SPSite(SiteURL))
            {
                using (new Microsoft.SharePoint.SPServiceContextScope(
                    SPServiceContext.GetContext(site)))
                {
                    BdcService service =
                        SPFarm.Local.Services.GetValue<BdcService>(
                        String.Empty);
                    IMetadataCatalog catalog =
                        service.GetDatabaseBackedMetadataCatalog(
                        SPServiceContext.Current);

                    IEntity entity = catalog.GetEntity(
                        nameSpace, entityName);
                    ILobSystemInstance LobSysteminstance =
                        entity.GetLobSystem().
                        GetLobSystemInstances()[0].Value;

                    // Accept the user input for identity value
                    Console.Write(
                        "\nEnter identity value for which you want to edit : ");
                    int identityColumnValue =
                        int.Parse(Console.ReadLine());
                    Identity identity =
                        new Identity(identityColumnValue);

                    try
                    {
                        IEntityInstance ientityinstance =
                            entity.FindSpecific(
                            identity, "Read Item", LobSysteminstance);
                        IFieldCollection fieldCollection =
                            entity.GetFinderView("Read List").Fields;

                        //Display the old values
                        Console.WriteLine("\nOld Values : ");

                        foreach (IField field in fieldCollection)
                        {
                            Console.WriteLine(
                                field.Name.PadRight(20) + ":" +
                                ientityinstance[field.Name].ToString());
                        }

                        // The following will work only for Sales.Customer table in AdventureWorks2008
                        // Changing value of "TerritoryID" field
                        string fieldName = "TerritoryID";
                        
                        // Example Value for TerritoryID will be 1,4,6 etc.
                        Console.Write(
                           "\nEnter the new value for the column {0}: ",
                           fieldName);
                        ientityinstance[fieldName] = int.Parse(Console.ReadLine());
                        ientityinstance["ModifiedDate"] = DateTime.Now;

                        ientityinstance.Update();
                        Console.WriteLine("Record updated");
                        
                        //Display the Updated values
                        Console.WriteLine("\nUpdated Values : ");

                        foreach (IField field in fieldCollection)
                        {
                            Console.WriteLine(
                                field.Name.PadRight(20) + ":" +
                                ientityinstance[field.Name].ToString());
                        }

                    }
                    catch (ObjectNotFoundException exception)
                    {
                        Console.WriteLine(
                            "Identity column with value {0} not found...",
                            identityColumnValue);
                    }

                }
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

См. также

Ссылка

BdcService

Services

IMetadataCatalog

GetDatabaseBackedMetadataCatalog(SPServiceContext)

GetEntity(String, String)

IEntity

GetLobSystem()

GetLobSystemInstances()

ILobSystemInstance

Identity

IEntityInstance

FindSpecific(Identity, String, ILobSystemInstance)

GetFinderView(String)

IView

Fields

IFieldCollection

Update()