Megosztás a következőn keresztül:


Inserting and Updating Data

This is the final task of the Entity Framework Quickstart. In this task, you will save changes made to Course objects bound to the DataGridView control to the database. You will also run the completed Course Manager application.

To save changes made to objects

  1. In the Toolbox, expand Common Controls, drag the Button control to the CourseViewer form designer, change the name of the control to saveChanges, and change the Text value to Update.

  2. In the CourseViewer form designer, double-click the saveChanges control.

    This creates the saveChanges_Click event handler method.

  3. Paste the following code that saves object changes to the database.

    Try
        ' Save object changes to the database, 
        ' display a message, and refresh the form.
        schoolContext.SaveChanges()
        MessageBox.Show("Changes saved to the database.")
        Me.Refresh()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
    
    try
    {
    
        // Save object changes to the database, 
        // display a message, and refresh the form.
        schoolContext.SaveChanges();
        MessageBox.Show("Changes saved to the database.");
        this.Refresh();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    

To close connections by disposing the long-running object context

  • In the closeForm_Click event handler method, type the following code. This code disposes of the object context before the form is closed.

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

To build and run the Class Scheduling application

  1. From the Debug menu, select Start Debugging or Start Without Debugging.

    This builds and starts the application.

  2. When the form loads, select a department from the ComboBox control.

    This displays the courses that belong to that department.

  3. In the DataGridView, update course information or add a new course and then click Update.

    This saves changes to the database and displays a message box to indicate that changes have been saved.

Next Steps

You have successfully created and run the Course Manager application. You have also completed this Entity Framework quickstart.

See Also

Concepts

Creating, Adding, Modifying, and Deleting Objects
ADO.NET Entity Framework

Other Resources

Samples
ADO.NET Entity Data Model Tools