データ定義言語の操作

.NET Framework バージョン 4 以降の Entity Framework では、データ定義言語 (DDL) がサポートされています。 これにより、接続文字列、およびストレージ (SSDL) モデルのメターデータに基づいて、データベース インスタンスを作成または削除できます。

ObjectContext の次のメソッドでは、接続文字列と SSDL の内容を使用して、データベースの作成と削除、データベースが存在するかどうかの確認、生成された DDL スクリプトの表示を実行します。

Note

DDL コマンドを実行するには、十分なアクセス許可が必要です。

上記に示したメソッドは、ほとんどの作業を基になる ADO.NET データ プロバイダーに委任します。 データベース オブジェクトの生成に使用される名前付け規則が、照会および更新に使用される規則と一致していることは、プロバイダーによって保証されています。

次の例は、既存のモデルを基にデータベースを生成する方法を示しています。 また、新しいエンティティ オブジェクトはオブジェクト コンテキストに追加され、データベースに保存されます。

プロシージャ

既存のモデルに基づいてデータベースを定義するには

  1. コンソール アプリケーションを作成します。

  2. 既存のモデルをアプリケーションに追加します。

    1. SchoolModel という名前の空のモデルを追加します。 空のモデルを作成する方法については、「方法: 新しい .edmx ファイルを作成する」トピックをご覧ください。

    SchoolModel.edmx ファイルがプロジェクトに追加されます。

    1. School モデル」から、School モデルの概念、ストレージ、マッピングの内容をコピーします。

    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