使用資料定義語言

從 .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