Coding the Form Constructor and Destructor

Before you can work with Customer objects, you need to connect to the database. This is provided by a JoobContext object.

The simplest JoobContext constructor is the default no-parameters constructor, which uses the defaultConnection element from the application configuration file.

To establish a connection, simply create a JoobContext object as follows.

JoobContext context = new JoobContext();

When a connection is no longer needed, dispose of the JoobContext object.

context.Dispose();

If a form utilizes the connection for the entire time it is shown, the form should have a reference to a context object. This reference is available to all code in the form. You can create the context object when the form is opened and dispose of this object when the form is closed.

If the form requires an occasional connection to the JADE database only (perhaps only if a specific button on the form is clicked), you can establish a temporary connection by creating a context object in a using block, as follows.

using (JoobContext context = new JoobContext())
{
    // access the database
}

Another object that is used throughout the application is the root object. The JoobContext object provides a way of accessing this object using a template method that can return the first instance of any class. The first (and only) instance of the Bank class is the root object.

bank = context.FirstInstance<Root>();

In the following instructions, a context object is created for the life of the form and a reference to the root object established.

  1. In the MainWindow.xaml.cs code file, add private member variables called context and bank to the MainWindow class for the context object and the root object, respectively.

    public partial class MainWindow: Window
    {
        private JoobContext context;
        private Bank bank;
  2. In the form constructor, initialize the context and bank references.

    public MainWindow()
    {
        InitializeComponent();
        context = new JoobContext();
        bank = context.FirstInstance<Bank>();
    }
  3. Add a form destructor to dispose the JoobContext object.

    ~MainWindow()
    {
        context.Dispose();
    }