Share via


Tipos (metadatos)

Los tipos son las construcciones de nivel superior que forman la base de un Entity Data Model (EDM). ADO.NET proporciona el espacio de nombres System.Data.Metadata.Edm, que contiene un conjunto de tipos que representan los conceptos definidos en el EDM en Entity Framework. Para obtener más información acerca de los modelos que se usan en Entity Framework, vea Modelado de datos en Entity Framework y Introducción al área de trabajo de metadatos.

Según se describe en el tema Introducción a la jerarquía de tipos de metadatos, un EdmType es una clase base para las clases que representan tipos en el EDM. Los tipos de nivel superior como SimpleType, StructuralType, CollectionType y RefType, se derivan de EdmType.

  • SimpleType describe los tipos primitivos. Para obtener más información sobre los tipos simples, vea Tipos simples (metadatos).

  • StructuralType es un tipo base para todos los tipos de la jerarquía de tipos de metadatos que tienen miembros. Para obtener más información acerca de los tipos estructurales, vea Tipos estructurales (metadatos).

  • CollectionType describe una colección de instancias de un tipo específico.

  • RefType contiene la dirección de una entidad para las operaciones que usan la entidad.

El tema Tipos del Entity Data Model también proporciona información detallada acerca de cómo se usan los tipos en el EDM.

En los ejemplos de código siguientes se muestra cómo obtener un área de trabajo de metadatos desde la conexión que después se usa para recuperar información acerca de un tipo concreto y de todos los demás tipos del modelo especificado. En los ejemplos de código se usa un CSpace y un SSpace para especificar el modelo. CSpace representa el nombre predeterminado del modelo conceptual. SSpace representa el nombre predeterminado del modelo de almacenamiento. Observe que el área de trabajo de metadatos es un componente del servicio en tiempo de ejecución que proporciona compatibilidad para recuperar los metadatos.

En los ejemplos de código siguientes se usa el modelo de Adventureworks que se proporciona en el tema Modelo completo (EDM) de AdventureWorks. Para obtener un ejemplo del archivo de configuración de la aplicación, vea Usar el modelo de objetos de 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

En esta sección

Vea también

Conceptos

Jerarquía de tipos de metadatos
Introducción a la jerarquía de tipos de metadatos
Tipos del Entity Data Model