다음을 통해 공유


데이터 정의 언어 사용

.NET Framework 버전 4부터 Entity Framework는 DDL(데이터 정의 언어)을 지원합니다. 이렇게 하면 연결 문자열 및 스토리지(SSDL) 모델의 메타데이터를 기반으로 데이터베이스 인스턴스를 만들거나 삭제할 수 있습니다.

연결 문자열 및 SSDL 콘텐츠를 사용하여 다음을 수행하는 방법은 ObjectContext 데이터베이스를 만들거나 삭제하고, 데이터베이스가 있는지 확인하고, 생성된 DDL 스크립트를 확인합니다.

비고

DDL 명령을 실행하면 충분한 권한이 있다고 가정합니다.

이전에 나열된 메서드는 대부분의 작업을 기본 ADO.NET 데이터 공급자에게 위임합니다. 데이터베이스 개체를 생성하는 데 사용되는 명명 규칙이 쿼리 및 업데이트에 사용되는 규칙과 일치하는지 확인하는 것은 공급자의 책임입니다.

다음 예제에서는 기존 모델을 기반으로 데이터베이스를 생성하는 방법을 보여줍니다. 또한 개체 컨텍스트에 새 엔터티 개체를 추가한 다음 데이터베이스에 저장합니다.

절차

기존 모델을 기반으로 데이터베이스를 정의하려면

  1. 콘솔 애플리케이션을 만듭니다.

  2. 애플리케이션에 기존 모델을 추가합니다.

    1. 라는 SchoolModel빈 모델을 추가합니다. 빈 모델을 만들려면 방법: 새 .edmx 파일 만들기 항목을 참조하세요.

    SchoolModel.edmx 파일이 프로젝트에 추가됩니다.

    1. 학교 모델 항목에서 학교 모델의 개념적, 스토리지 및 매핑 콘텐츠를 복사합니다.

    2. SchoolModel.edmx 파일을 열고 태그 내에 edmx:Runtime 콘텐츠를 붙여넣습니다.

  3. 주 함수에 다음 코드를 추가합니다. 이 코드는 데이터베이스 서버에 대한 연결 문자열을 초기화하고, DDL 스크립트를 보고, 데이터베이스를 만들고, 컨텍스트에 새 엔터티를 추가하고, 변경 내용을 데이터베이스에 저장합니다.

    // Initialize the connection string.
    String connectionString = "...";
    
    using (SchoolEntities context = new SchoolEntities(connectionString))
    {
        try
        {
            if (context.DatabaseExists())
            {
                // Make sure the database instance is closed.
                context.DeleteDatabase();
            }
            // View the database creation script.
            Console.WriteLine(context.CreateDatabaseScript());
            // Create the new database instance based on the storage (SSDL) section
            // of the .edmx file.
            context.CreateDatabase();
    
            // The following code adds a new objects to the context
            // and saves the changes to the database.
            Department dpt = new Department
            {
                Name = "Engineering",
                Budget = 350000.00M,
                StartDate = DateTime.Now
            };
    
            context.Departments.AddObject(dpt);
            // An entity has a temporary key
            // until it is saved to the database.
            Console.WriteLine(dpt.EntityKey.IsTemporary);
            context.SaveChanges();
            // The object was saved and the key
            // is not temporary any more.
            Console.WriteLine(dpt.EntityKey.IsTemporary);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine(ex.InnerException.Message);
        }
        catch (NotSupportedException ex)
        {
            Console.WriteLine(ex.InnerException.Message);
        }
     }
    
    ' Initialize the connection string.
    Dim connectionString As String =
        "metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;" &
        "provider connection string=""Data Source=.;Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True"""
    
    Using context As New SchoolEntities(connectionString)
        Try
            If context.DatabaseExists() Then
                ' Make sure the database instance is closed.
                context.DeleteDatabase()
            End If
            ' View the database creation script.
            Console.WriteLine(context.CreateDatabaseScript())
            ' Create the new database instance based on the storage (SSDL) section
            ' of the .edmx file.
            context.CreateDatabase()
    
            ' The following code adds a new objects to the context
            ' and saves the changes to the database.
            Dim dpt As New Department()
    
            context.Departments.AddObject(dpt)
            ' An entity has a temporary key
            ' until it is saved to the database.
            Console.WriteLine(dpt.EntityKey.IsTemporary)
            context.SaveChanges()
    
            ' The object was saved and the key
            ' is not temporary any more.
            Console.WriteLine(dpt.EntityKey.IsTemporary)
    
        Catch ex As InvalidOperationException
            Console.WriteLine(ex.InnerException.Message)
        Catch ex As NotSupportedException
            Console.WriteLine(ex.InnerException.Message)
        End Try
    End Using