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


Типы (метаданные)

Типы являются конструкциями верхнего уровня, формирующими основу модели Entity Data Model (EDM). Технология ADO.NET обеспечивает пространство имен System.Data.Metadata.Edm, которое содержит набор типов, представляющих основные понятия, определенные в модели EDM в платформе Entity Framework. Дополнительные сведения о моделях, использующихся в платформе Entity Framework, см. в разделах Моделирование данных на платформе Entity Framework и Общие сведения о рабочей области метаданных.

Как описано в разделе Общие сведения об иерархии типов метаданных, тип EdmType является базовым для классов, представляющих типы в модели EDM. Такие типы верхнего уровня, как SimpleType, StructuralType, CollectionType и RefType, являются производными от типа EdmType.

  • Тип SimpleType описывает типы-примитивы. Дополнительные сведения о типах-примитивах см. в разделе Простые типы (метаданные).

  • Тип StructuralType является базовым для всех типов в иерархии типов метаданных, имеющих элементы. Дополнительные сведения о структурных типах см. в разделе Структурные типы (метаданные).

  • Тип CollectionType описывает коллекцию экземпляров определенного типа.

  • Тип RefType содержит адрес сущности для операций с этой сущностью.

В разделе Типы модели EDM также представлены подробные сведения об использовании типов в модели EDM.

В следующем образце кода показано, как возвратить рабочую область метаданных из соединения и использовать ее для получения сведений о конкретном типе и всех других типах в заданной модели. В образцах кода для задания модели используются типы CSpace и SSpace. Элемент CSpace представляет собой имя по умолчанию для концептуальной модели. Имя SSpace используется по умолчанию для модели хранения. Обратите внимание, что рабочая область метаданных — это служебный компонент времени выполнения, который обеспечивает поддержку извлечения метаданных.

В образцах кода используется модель AdventureWorks, приведенная в разделе Полная модель AdventureWorks (модель EDM). Пример файла конфигурации приложения см. в разделе Использование модели объектов AdventureWorks (модель EDM).

// The first example:
using System;
using System.Data;
using System.Data.EntityClient;
using System.Collections.ObjectModel;
using System.Data.Metadata.Edm;

class GetTypeExample
{
  static void Main()
  {
    try
    {
      // Establish a connection to the underlying data provider by 
      // using the connection string specified in the config file.
      using (EntityConnection connection = 
         new EntityConnection("Name=AdventureWorksEntities"))
      {
        // Open the connection.
        connection.Open();

        // Access the metadata workspace.
        MetadataWorkspace workspace = 
              connection.GetMetadataWorkspace();

        // Get an EntityType object by using the specified type name, 
        // the namespace name, and the model. 
        EdmType departmentType1 = workspace.GetType(
              "Department", "AdventureWorksModel", DataSpace.CSpace);

        Console.WriteLine(
           "Type found in the conceptual model Name: {0}, {1} ",
           departmentType1.Name, 
           departmentType1.NamespaceName);

        // Get an EntityType object by using the specified type name, 
        // the namespace name, and the model. 
        EdmType departmentType2 = workspace.GetType( 
           "Department", "AdventureWorksModel.Store",
           DataSpace.SSpace);

        Console.WriteLine(
          "Type found in the storage model Name: {0}, {1} ",
          departmentType2.Name,
          departmentType2.NamespaceName);
      }
    }
    catch (MetadataException exceptionMetadata)
    {
      Console.WriteLine("MetadataException: {0}", 
                       exceptionMetadata.Message);
    }
    catch (System.Data.MappingException exceptionMapping)
    {
      Console.WriteLine("MappingException: {0}",
                       exceptionMapping.Message);
    }
  }
}
// The second example:
using System;
using System.Data;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using System.Collections.ObjectModel;

class GetTypesExample
{
  static void Main()
  {
    try
    {
       // Establish a connection to the underlying data provider by 
       // using the connection string specified in the config file.
       using (EntityConnection connection = 
           new EntityConnection("Name=AdventureWorksEntities"))
       {
          // Open the connection.
          connection.Open();

          // Access the metadata workspace.
          MetadataWorkspace workspace = 
               connection.GetMetadataWorkspace();

          // Get types from the conceptual model.
          GetTypesFromModel(workspace, DataSpace.CSpace);

          // Get types from the storage model.
          GetTypesFromModel(workspace, DataSpace.SSpace);
       }
    }
    catch (MetadataException exceptionMetadata)
    {
      Console.WriteLine("MetadataException: {0}", 
                       exceptionMetadata.Message);
    }
    catch (System.Data.MappingException exceptionMapping)
    {
       Console.WriteLine("MappingException: {0}",
                        exceptionMapping.Message);
    }
  }

  public static void GetTypesFromModel(
    MetadataWorkspace workspace, DataSpace model)
  {
    // Get a collection of the EdmTypes. 
    // An EdmType class is the base class for the classes 
    // that represent types in the Entity Data Model (EDM).
    ReadOnlyCollection<EdmType> types =
          workspace.GetItems<EdmType>(model);

    // Iterate through the collection to get each edm type, 
    // specifically each entity type.
    foreach (EdmType item in types)
    {
       EntityType entityType = item as EntityType;
       if (entityType != null)
       {
          Console.WriteLine("Type: {0}, Type in Model: {1} ",
                item.GetType().FullName, item.FullName);
       }
     }
  }
}
' The first example:
Imports System
Imports System.Data
Imports System.Data.EntityClient
Imports System.Data.Metadata.Edm

Class GetTypeExample
   Shared Sub Main()
     Try
       ' Establish a connection to the underlying data provider by 
       ' using the connection string specified in the config file.
       Using connection As EntityConnection = _
          New EntityConnection("Name=AdventureWorksEntities")

          ' Open the conection.
          connection.Open()

          ' Access the metadata workspace.
           Dim workspace As MetadataWorkspace = _
             connection.GetMetadataWorkspace

           ' Get an EntityType object by using the specified type name, 
           ' the namespace name, and the model. 
           Dim departmentType1 As EdmType = _
              workspace.GetType("Department", "AdventureWorksModel", _
              DataSpace.CSpace)
           Console.WriteLine( _
           "Type found in the conceptual model Name: {0}, {1} ", _
           departmentType1.Name, _
           departmentType1.NamespaceName)

           ' Get an EntityType object by using the specified type name, 
           ' the namespace name, and the model. 
           Dim departmentType2 As EdmType = _
               workspace.GetType("Department", _
               "AdventureWorksModel.Store", _
               DataSpace.SSpace)
           Console.WriteLine( _
              "Type found in the storage model Name: {0}, {1} ", _
              departmentType2.Name, _
              departmentType2.NamespaceName)
        End Using
     Catch exceptionMetadata As MetadataException
        Console.WriteLine("MetadataException: {0}", _
          exceptionMetadata.Message)
     Catch exceptionMapping As MappingException
        Console.WriteLine("MappingException: {0}", _
          exceptionMapping.Message)
     End Try
   End Sub
End Class
' The second example:
Imports System
Imports System.Collections.ObjectModel
Imports System.Data
Imports System.Data.EntityClient
Imports System.Data.Metadata.Edm

Class GetTypesExample
   Shared Sub Main()
     Try
       ' Establish a connection to the underlying data provider by 
       ' using the connection string specified in the config file.
       Using connection As EntityConnection = _
          New EntityConnection("Name=AdventureWorksEntities")

         ' Open the conection.
         connection.Open()

         ' Access the metadata workspace.
         Dim workspace As MetadataWorkspace = _
           connection.GetMetadataWorkspace

         ' Get types from the conceptual model.
         GetTypesFromModel(workspace, DataSpace.CSpace)

         ' Get types from the storage model.
         GetTypesFromModel(workspace, DataSpace.SSpace)
       End Using
     Catch exceptionMetadata As MetadataException
        Console.WriteLine("MetadataException: {0}", _
          exceptionMetadata.Message)
     Catch exceptionMapping As MappingException
        Console.WriteLine("MappingException: {0}", _
          exceptionMapping.Message)
     End Try
   End Sub

  Public Shared Sub GetTypesFromModel( _
     ByVal workspace As MetadataWorkspace, ByVal model As DataSpace)
     ' Get a collection of the EdmTypes. 
     ' An EdmType class is the base class for the classes 
     ' that represent types in the Entity Data Model (EDM).
     Dim types As ReadOnlyCollection(Of EdmType) = _
         workspace.GetItems(Of EdmType)(model)
     Dim item As EdmType

     ' Iterate through the collection to get each edm type, 
     ' specifically each entity type.
     For Each item In types
       Dim entityType As EntityType = TryCast(item, EntityType)
       If (Not entityType Is Nothing) Then
         Console.WriteLine("Type: {0}, Type in Model: {1} ", _
             item.GetType.FullName, item.FullName)
        End If
     Next
   End Sub
End Class

В этом разделе

См. также

Основные понятия

Иерархия типов метаданных
Общие сведения об иерархии типов метаданных
Типы модели EDM