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


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

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

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

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

Описание

В следующем примере кода показано, как программно выполнить экземпляр метода Deleter внешнего типа контента с помощью объектной модели среды выполнения 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)
        {
            BDCDelete();
        }

        //How To: Edit an item from an External Content Type
        public static void BDCDelete()
        {
            //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 delete : ");
                    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 item

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

                        Console.Write("\nDo you want to delete this record (Y/N)?");

                        string confirmDelete = Console.ReadLine();

                        if (string.Compare(confirmDelete, "Y", true) == 0)
                        {
                            ientityinstance.Delete();
                            Console.WriteLine("Record deleted");
                        }

                    }
                    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