다음을 통해 공유


엔터티 연결 및 메타데이터 작업 영역

ADO.NET 엔터티 프레임워크를 사용하는 응용 프로그램을 개발하는 동안 EntityConnection 개체를 사용하여 데이터베이스에 연결할 수 있습니다. EDM(엔터티 데이터 모델)에서 EntityConnection 클래스의 새 인스턴스를 만드는 경우 app.config 파일에 연결 문자열을 지정할 수 있습니다. 연결 문자열은 필요한 모델과 매핑뿐 아니라 저장소별 데이터 공급자 이름 및 연결 문자열이 포함된 메타데이터 집합을 참조합니다.

EntityConnection에 대한 생성자에는 EntityConnectionEntityConnection이 포함됩니다. EntityConnection는 메타데이터 및 데이터베이스 연결을 참조하는 연결 문자열을 단일 매개 변수로 사용합니다. EntityConnection 생성자는 기존 MetadataWorkspace 개체와 데이터베이스 연결 문자열을 사용합니다. 이 경우 디스크에 저장된 파일 또는 어셈블리의 포함 리소스와는 다른 소스의 메타데이터를 기반으로 EntityConnection을 만드는 키 시나리오가 가능합니다.

EntityConnection 인스턴스는 개념적 모델 및 저장소 모델에 대한 메타데이터와 두 모델 간의 매핑을 정의하는 MetadataWorkspace에 대한 참조를 유지합니다. 연결 문자열을 변경하면 적합한 메타데이터가 포함된 새 메타데이터 작업 영역이 만들어집니다.

Note참고

연결 문자열을 변경하면 메타데이터 캐시가 아티팩트 경로, 공급자 이름 및 공급자 연결 문자열에 키 지정되므로 메타데이터 작업 영역의 다른 인스턴스가 만들어집니다. 공급자 연결 문자열이 다르면 캐시 항목도 달라집니다.

EntityConnection 클래스의 인스턴스나 ObjectContext 클래스의 특수 버전에서 MetadataWorkspace 클래스의 인스턴스를 검색할 수 있습니다. ObjectContext 클래스는 ADO.NET과 데이터베이스 사이의 연결을 캡슐화하고 만들기, 읽기, 업데이트 및 삭제 작업을 위한 게이트웨이 역할을 수행합니다. ADO.NET 엔터티 프레임워크를 사용하여 응용 프로그램을 빌드하는 경우 엔터티 프레임워크는 ObjectContext에서 파생된 클래스를 자동으로 생성합니다.

다음 코드 샘플에서는 MetadataWorkspace 개체를 검색하는 두 가지 방법을 보여 줍니다. 샘플의 첫 번째 코드 예제에서는 MetadataWorkspace 클래스의 인스턴스를 EntityConnection 클래스의 인스턴스에서 명시적으로 검색합니다. 샘플의 두 번째 코드 예제에서는 MetadataWorkspace 클래스의 인스턴스를 ObjectContext 클래스의 특수 버전에서 암시적으로 검색합니다. 코드 샘플에서는 AdventureWorks 전체 모델(EDM)에서 설명하는 Adventureworks 모델을 사용합니다. 응용 프로그램 구성 파일의 예제를 보려면 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

참고 항목

개념

메타데이터 작업 영역