Condividi tramite


Connessione di entità e area di lavoro metadati

Durante lo sviluppo di un'applicazione che utilizza ADO.NET Entity Framework, è possibile utilizzare un oggetto EntityConnection per connettersi a un database. Quando si crea una nuova istanza della classe EntityConnection in Entity Data Model (EDM), è possibile specificare una stringa di connessione in un file app.config. La stringa di connessione fa riferimento un insieme di metadati che contiene i mapping e i modelli necessari, nonché un nome di provider di dati specifici dell'archiviazione e una stringa di connessione.

I costruttori per EntityConnection includono EntityConnection e EntityConnection. EntityConnection accetta una stringa di connessione che fa riferimento ai metadati e una connessione al database in un singolo parametro. Il costruttore EntityConnection accetta un oggetto MetadataWorkspace esistente e una stringa di connessione al database. Questo rende possibile uno scenario principale di creazione di un oggetto EntityConnection basato su metadati di un'origine diversa da un file su un disco o come risorsa incorporata nell'assembly.

Ogni istanza di EntityConnection contiene un riferimento all'oggetto MetadataWorkspace che descrive i metadati sui modelli concettuali e di archiviazione e il mapping tra di essi. Quando si modifica la stringa di connessione, viene creata una nuova area di lavoro di metadati che contiene i metadati appropriati.

NoteNota

Eventuali modifiche in una stringa di connessione creano un'istanza differente dell'area di lavoro metadati perché la cache dei metadati si basa sui percorsi di elementi, sul nome del provider e sulla stringa di connessione del provider. Se la stringa di connessione del provider è diversa, le voci della cache saranno diverse.

È possibile recuperare un'istanza della classe MetadataWorkspace da un'istanza della classe EntityConnection o da una versione specializzata della classe ObjectContext. La classe ObjectContext incapsula una connessione tra ADO.NET e il database, servendo da gateway per le operazioni di creazione, lettura, aggiornamento ed eliminazione. Quando si compila l'applicazione utilizzando ADO.NET Entity Framework, Entity Framework genera automaticamente una classe derivata da ObjectContext.

Nell'esempio di codice seguente sono illustrati due modi per recuperare un oggetto MetadataWorkspace. Il primo esempio di codice incluso nell'esempio consente di recuperare in modo esplicito un'istanza della classe MetadataWorkspace dall'istanza della classe EntityConnection. Il secondo esempio di codice incluso nell'esempio consente di recuperare in modo implicito un'istanza della classe MetadataWorkspace da una versione specializzata della classe ObjectContext. Nell'esempio di codice viene utilizzato il modello AdventureWorks descritto in Modello completo di AdventureWorks (EDM). Per un esempio del file di configurazione dell'applicazione, vedere Utilizzo del modello a oggetti di AdventureWorks (EDM).

using System;
using System.Data;
using System.Data.Objects;
using System.Collections.ObjectModel;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using AdventureWorksModel;

class MetadataWorkspaceExample
{
  static void Main()
  {
    try
    {
       // Retrieve a MetadataWorkspace from the EntityConnection:
       // The input parameter for an EntityConnection is a 
       // connection string that refers to the location of the 
       // XML files containing the persistent representation of 
       // metadata.
       // 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"))
       {
          // Get the metadata workspace from the connection.
          MetadataWorkspace workspace = 
                     connection.GetMetadataWorkspace();

          // Get a collection of the entity containers.
          ReadOnlyCollection<EntityContainer> containers = 
                   workspace.GetItems<EntityContainer>(
                                      DataSpace.CSpace);

          // Iterate through the collection to get 
          // each entity container.
          foreach (EntityContainer container in containers)
          {
              Console.WriteLine("EntityContainer Name: {0} ", 
                               container.Name);
          }
       }
     }
     catch (MetadataException exceptionMetadata)
     {
        Console.WriteLine("MetadataException: {0}", 
                         exceptionMetadata.Message);
     }
     catch (System.Data.MappingException exceptionMapping)
     {
        Console.WriteLine("MappingException: {0}",
                         exceptionMapping.Message);
     }

     try
     {
        // Retrieve a MetadataWorkspace from an ObjectContext:
        // AdventureworksContext represents the ADO.NET ObjectContext 
        // that acts as a factory for queries; 
        // tracks object state; and is used to initiate updates 
        // against the database.
        using (
          AdventureWorksEntities db = new AdventureWorksEntities ())
        {
           // Dereference the workspace from the AdventureWorksEntities 
           // class (an ObjectContext specialization).
           MetadataWorkspace workspace = db.MetadataWorkspace;

           // Get a collection of the entity containers.
           ReadOnlyCollection<EntityContainer> containers = 
                    workspace.GetItems<EntityContainer>(
                                    DataSpace.CSpace);

           // Iterate through the collection to get 
           // each entity container.
           foreach (EntityContainer container in containers)
           {
               Console.WriteLine(
                    "EntityContainer Name: {0} ", 
                    container.Name);
            }
        }
     }
     catch (MetadataException exceptionMetadata)
     {
        Console.WriteLine("MetadataException: {0}", 
                         exceptionMetadata.Message);
     }
     catch (System.Data.MappingException exceptionMapping)
     {
        Console.WriteLine("MappingException: {0}",
                         exceptionMapping.Message);
     }
  }
}
Imports System
Imports System.Data
Imports System.Collections.ObjectModel
Imports System.Data.EntityClient
Imports System.Data.Metadata.Edm
Imports AdventureWorksModel

Class MetadataWorkspaceExample

  Public Shared Sub Main()
   Try
     ' Retrieve a MetadataWorkspace from the EntityConnection:
     ' The input parameter for an EntityConnection is a 
     ' connection string that refers to the location of the 
     ' XML files containing the persistent representation of 
     ' metadata.
     ' 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")

        ' Get the metadata workspace from the connection.
        Dim workspace As MetadataWorkspace = _
           connection.GetMetadataWorkspace()

        ' Get a collection of the entity containers.
        Dim containers As ReadOnlyCollection(Of EntityContainer)
        containers = _
           workspace.GetItems(Of EntityContainer)(DataSpace.CSpace)

        ' Iterate through the collection to get 
        ' each entity container.
        Dim container As EntityContainer
        For Each container In containers
          Console.WriteLine("EntityContainer Name: {0} ", _
              container.Name)
        Next
     End Using
   Catch exceptionMetadata As MetadataException
     Console.WriteLine("MetadataException: {0}", _
        exceptionMetadata.Message)
   Catch exceptionMapping As MappingException
     Console.WriteLine("MappingException: {0}", _
          exceptionMapping.Message)
   End Try

   Try
     ' Retrieve a MetadataWorkspace from an ObjectContext:
    ' AdventureworksContext represents the ADO.NET ObjectContext that 
    ' acts as a factory for queries; 
    ' tracks object state; and is used to initiate updates 
    ' against the database.
    Using db As AdventureWorksEntities = New AdventureWorksEntities
      ' Dereference the workspace from the AdventureWorksEntities class
      ' (an ObjectContext specialization).
      Dim workspace As MetadataWorkspace = db.MetadataWorkspace

      ' Get a collection of the entity containers.
      Dim containers As ReadOnlyCollection(Of EntityContainer)
      containers = _
         workspace.GetItems(Of EntityContainer)(DataSpace.CSpace)

      ' Iterate through the collection to get 
      ' each entity container.
      Dim container As EntityContainer
      For Each container In containers
        Console.WriteLine("EntityContainer Name: {0} ", container.Name)
      Next
    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

Vedere anche

Concetti

Area di lavoro metadati