다음을 통해 공유


데이터 정의 언어로 작업

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

ObjectContext의 다음 메서드는 연결 문자열과 SSDL 콘텐츠를 사용하여 데이터베이스를 만들거나 삭제하고, 데이터베이스가 있는지 확인하며, 생성된 DDL 스크립트를 확인합니다.

참고 항목

DDL 명령을 실행하려면 충분한 권한이 있어야 합니다.

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

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

절차

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

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

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

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

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

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

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

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

    // Initialize the connection string.
    String connectionString = "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 (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