Bagikan melalui


Menggunakan Bahasa Definisi Data

Dimulai dengan .NET Framework versi 4, Entity Framework mendukung bahasa definisi data (DDL). Ini memungkinkan Anda membuat atau menghapus instans database berdasarkan string koneksi dan metadata model penyimpanan (SSDL).

Metode berikut di ObjectContext menggunakan string koneksi dan konten SSDL untuk melakukan hal berikut: membuat atau menghapus database, memeriksa apakah database ada, dan melihat skrip DDL yang dihasilkan:

Catatan

Menjalankan perintah DDL mengasumsikan izin yang memadai.

Metode yang sebelumnya terdaftar mendelegasikan sebagian besar pekerjaan ke penyedia data ADO.NET yang mendasarinya. Penyedia bertanggung jawab untuk memastikan bahwa konvensi penamaan yang digunakan untuk menghasilkan objek database konsisten dengan konvensi yang digunakan untuk kueri dan pembaruan.

Contoh berikut menunjukkan cara membuat database berdasarkan model yang ada. Hal ini juga menambahkan objek entitas baru ke konteks objek dan kemudian menyimpannya ke database.

Prosedur

Untuk menentukan database berdasarkan model yang sudah ada

  1. Buat aplikasi konsol

  2. Tambahkan model yang ada ke aplikasi Anda.

    1. Tambahkan model kosong bernama SchoolModel. Untuk membuat model kosong, lihat topik Cara: Membuat File .edmx Baru.

    File SchoolModel.edmx ditambahkan ke proyek Anda.

    1. Salin konten konseptual, penyimpanan, dan pemetaan untuk model Sekolah dari topik Model Sekolah.

    2. Buka file SchoolModel.edmx dan tempel konten di dalam tag edmx:Runtime.

  3. Tambahkan kode berikut ke fungsi utama Anda. Kode menginisialisasi string koneksi ke server database Anda, melihat skrip DDL, membuat database, menambahkan entitas baru ke konteks, dan menyimpan perubahan ke database.

    // 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