插入和更新数据(实体框架快速入门)

这是 Entity Framework 快速入门的最后一项任务。在此任务中,您将对与 DataGridView 控件绑定的 Course 对象所做的更改保存到数据库中。还将运行已完成的 Course Manager 应用程序。

保存对对象所做的更改

  1. 在**“工具箱”中,展开“公共控件”,将“按钮”**控件拖到 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();
    

生成并运行类计划应用程序

  1. 从**“调试”菜单中,单击“开始调试”“开始执行(不调试)”**。

    此时将生成并启动应用程序。

  2. 当加载窗体时,从 ComboBox 控件中选择一个系。

    此时将显示属于该系的课程。

  3. DataGridView 中,更新课程信息或添加新课程,然后单击 Update

    此时会将更改保存到数据库中,并显示一个消息框,其中声明已保存的更改数。

后续步骤

您已成功地创建并运行了 Course Manager 应用程序。您还完成了这一 实体框架 快速入门。有关 实体框架 的更多信息,请参见对象服务(实体框架) 中的其他主题。

另请参见

其他资源

示例(实体框架)
对象服务(实体框架)
实体框架任务