Share via


插入及更新資料 (Entity Framework 快速入門)

這是 Entity Framework 快速入門的最後一項工作。在此工作中,您會將與 DataGridView 控制項繫結之 Course 物件的變更儲存到資料庫。您也將執行完成的 Course Manager 應用程式。

若要儲存對物件所做的變更

  1. 在 [工具箱] 中展開 [通用控制項]、將 [Button] 控制項拖曳至 CourseViewer 表單設計工具、將此控制項的名稱變更為 saveChanges,然後將 Text 值變更為 Update

  2. CourseViewer 表單設計工具中,按兩下 saveChanges 控制項。

    這樣會建立 saveChanges_Click 事件處理常式方法。

  3. 貼上可將物件變更儲存到資料庫的下列程式碼。

    Dim numChanges As New Integer
    Try
        ' Save object changes to the database, display a message, 
        ' and refresh the form.
        numChanges = schoolContext.SaveChanges()
        MessageBox.Show(numChanges.ToString() + _
            " change(s) saved to the database.")
        Me.Refresh()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    
    try
    {
        int numChanges;
        // Save object changes to the database, display a message,
        // and refresh the form.
        numChanges = schoolContext.SaveChanges();
        MessageBox.Show(numChanges.ToString() + 
            " change(s) saved to the database.");
        this.Refresh();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    

若要處置長期執行的物件內容來關閉連接

  • closeForm_Click 事件處理常式方法中,輸入下列程式碼。這段程式碼會在關閉表單之前處置物件內容。

    ' Dispose the object context.
    schoolContext.Dispose()
    
    // Dispose the object context.
    schoolContext.Dispose();
    

若要建置及執行 Class Scheduling 應用程式

  1. 從 [偵錯] 功能表,選取 [開始偵錯] 或 [啟動但不偵錯]。

    這樣會建置及啟動應用程式。

  2. 當此表單載入時,請從 ComboBox 控制項選取部門。

    這樣會顯示屬於該部門的課程。

  3. DataGridView 中,更新課程資訊或是加入新課程,然後按一下 Update

    這樣會將變更儲存到資料庫,並顯示一個訊息方塊來宣告儲存的變更數目。

後續的步驟

您已順利建立及執行 Course Manager 應用程式。您也已經完成這項 實體架構 快速入門。如需 實體架構 的詳細資訊,請參閱 物件服務 (Entity Framework) 中的其他主題。

另請參閱

其他資源

範例 (Entity Framework)
物件服務 (Entity Framework)
Entity Framework 工作