Compartir a través de


Entity Connection and Metadata Workspace

While developing an application that uses the ADO.NET Entity Framework, you can use an EntityConnection object to connect to a database. When you create a new instance of the EntityConnection class in the Entity Data Model (EDM), you can specify a connection string in an app.config file. The connection string references a set of metadata that contains the necessary models and mapping, and also a storage-specific data provider name and connection string.

Constructors for the EntityConnection include EntityConnection and EntityConnection. EntityConnection takes a connection string that references metadata and a database connection in a single parameter. The EntityConnection constructor takes an existing MetadataWorkspace object and a database connection string. This enables a key scenario of creating an EntityConnection based on metadata from a different source than a file on a disk or as an embedded resource in assembly.

Each EntityConnection instance holds a reference to the MetadataWorkspace that describes the metadata about the conceptual and storage models, and the mapping between the two. When you change the connection string, a new metadata workspace is created that contains the appropriate metadata.

Note

Any change in a connection string creates a different instance of the metadata workspace because the metadata cache is keyed on the artifact paths, provider name, and the provider connection string. If the provider connection string is different, the cache entries will be different.

You can retrieve an instance of the MetadataWorkspace class from an instance of the EntityConnection class or a specialized version of the ObjectContext class. The ObjectContext class encapsulates a connection between ADO.NET and the database, serving as a gateway for create, read, update, and delete operations. When you build your application by using the ADO.NET Entity Framework, the Entity Framework auto-generates a class derived from ObjectContext.

The following code sample demonstrates two ways to retrieve a MetadataWorkspace object. The first code example in the sample retrieves an instance of the MetadataWorkspace class from the instance of the EntityConnection class explicitly. The second code example in the sample retrieves an instance of the MetadataWorkspace class from a specialized version of the ObjectContext class implicitly. The code sample uses the Adventureworks model described in AdventureWorks Complete Model (EDM). For an example of the application config file, seeUsing the AdventureWorks Object Model (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

See Also

Concepts

Metadata Workspace