However, this approach has a few drawbacks:

    1. The Load method loads all data from the CUSTOMER table to memory at once

    2. Although lazy properties (INVOICES) are not loaded immediately, but only once they are accessed, they will be loaded anyway when the records are shown in the grid and it will happen each time a group of records is shown

    3. Record ordering is not defined

    To get around these drawbacks, we will use a feature of the LINQ (Language Integrated Query) technology, LINQ to Entities. LINQ to Entities offers a simple and intuitive approach to getting data using C# statements that are syntactically similar to SQL query statements. You can read about the LINQ syntax in .

    The LINQ extension methods can return two objects: IEnumerable and IQueryable. The IQueryable interface is inherited from IEnumerable so, theoretically, an IQueryable object is also an IEnumerable. In reality, they are distinctly different.

    The IEnumerable interface is in the System.Collections namespace. An IEnumerable object is a collection of data in memory that can be addressed only in a forward direction. During the query execution, IEnumerable loads all data. Filtering, if required, is done on the client side.

    The IQueryable interface is in the System.Linq namespace. It provides remote access to the database and movement through the data can be bi-directional. During the process of creating a query that returns an IQueryable object, the query is optimized to minimise memory usage and network bandwidth.

    The Local property returns the IEnumerable interface, through which we can create LINQ queries.

    1. private void LoadCustomersData()
    2. {
    3. var dbContext = AppVariables.getDbContext();
    4. dbContext.CUSTOMERS.Load();
    5. var customers =
    6. from customer in dbContext.CUSTOMERS.Local
    7. orderby customer.NAME
    8. select new customer;
    9. bindingSource.DataSource = customers.ToBindingList();
    10. }

    For a LINQ query to be converted into SQL and executed on the server, we need to access the dbContext.CUSTOMERS directly instead of accessing the dbContext.CUSTOMERS.Local property in the LINQ query. The prior call to dbContext.CUSTOMERS.Load(); to load the collection to memory is not required.

    IQueryable and BindingList

    IQueryable objects present a small problem: they cannot return BindingList. BindingList is a base class for creating a two-way data-binding mechanism. We can use the IQueryable interface to get a regular list by calling ToList but, this way, we lose handy features such as sorting in the grid and several more. The deficiency was fixed in .NET Framework 5 by creating a special extension. To do the same thing in FW4, we will create our own solution.

    Other Extensions

    There are several more extensions in the iQueryable interface:

    NextValueFor

    is used to get the next value from the generator.

    dbContext.Database.SqlQuery

    allows SQL queries to be executed directly and their results to be displayed on some entity (projection).

    DetachAll

    is used to detach all objects of the DBSet collection from the context. It is necessary to update the internal cache, because all retrieved data are cached and are not retrieved from the database again. However, that is not always useful because it makes it more difficult to get the latest version of records that were modified in another context.

    Refresh

    is used to update the properties of an entity object. It is useful for updating the properties of an object after it has been edited or added.

    Code for Loading the Data

    Our code for loading data will look like this:

    1. {
    2. var dbContext = AppVariables.getDbContext();
    3. // disconnect all loaded objects
    4. // this is necessary to update the internal cache
    5. // for the second and subsequent calls of this method
    6. dbContext.DetachAll(dbContext.CUSTOMERS);
    7. var customers =
    8. from customer in dbContext.CUSTOMERS
    9. orderby customer.NAME
    10. select customer;
    11. bindingSource.DataSource = customers.ToBindingList();
    12. private void CustomerForm_Load(object sender, EventArgs e)
    13. {
    14. LoadCustomersData();
    15. dataGridView.DataSource = bindingSource;
    16. dataGridView.Columns["INVOICES"].Visible = false;
    17. dataGridView.Columns["CUSTOMER_ID"].Visible = false;
    18. dataGridView.Columns["NAME"].HeaderText = "Name";
    19. dataGridView.Columns["ADDRESS"].HeaderText = "Address";
    20. dataGridView.Columns["ZIPCODE"].HeaderText = "ZipCode";
    21. dataGridView.Columns["PHONE"].HeaderText = "Phone";
    22. }
    Adding a Customer

    This is the code of the event handler for clicking the Add button:

    While adding the new record, we used the generator to get the value of the next identifier. We could have done it without applying the value of the identifier, leaving the BEFORE INSERT trigger to fetch the next value of the generator and apply it. However, that would leave us unable to update the added record.

    Editing a Customer

    The code of the event handler for clicking the Edit button is as follows:

    1. private void btnEdit_Click(object sender, EventArgs e) {
    2. var dbContext = AppVariables.getDbContext();
    3. // get instance
    4. var customer = (CUSTOMER)bindingSource.Current;
    5. // create an editing form
    6. using (CustomerEditorForm editor = new CustomerEditorForm()) {
    7. editor.Text = "Edit customer";
    8. editor.Customer = customer;
    9. // Form Close Handler
    10. editor.FormClosing += delegate (object fSender, FormClosingEventArgs fe) {
    11. if (editor.DialogResult == DialogResult.OK) {
    12. try {
    13. // trying to save the changes
    14. dbContext.SaveChanges();
    15. // update all related controls
    16. bindingSource.ResetCurrentItem();
    17. }
    18. catch (Exception ex) {
    19. // display error
    20. // Do not close the form to correct the error
    21. fe.Cancel = true;
    22. }
    23. }
    24. else
    25. bindingSource.CancelEdit();
    26. };
    27. // show the modal form
    28. editor.ShowDialog(this);
    29. }
    30. }

    The form for editing the customer looks like this:

    Figure 25. Customer edit form

    Deleting a Customer

    The code of the event handler for clicking the Delete button is as follows:

    1. private void btnDelete_Click(object sender, EventArgs e) {
    2. var dbContext = AppVariables.getDbContext();
    3. var result = MessageBox.Show("Are you sure you want to delete the customer?",
    4. "Confirmation",
    5. MessageBoxButtons.YesNo,
    6. MessageBoxIcon.Question);
    7. if (result == DialogResult.Yes) {
    8. // get the entity
    9. var customer = (CUSTOMER)bindingSource.Current;
    10. try {
    11. dbContext.CUSTOMERS.Remove(customer);
    12. // trying to save the changes
    13. dbContext.SaveChanges();
    14. // remove from the linked list
    15. bindingSource.RemoveCurrent();
    16. }
    17. catch (Exception ex) {
    18. // display error
    19. MessageBox.Show(ex.Message, "Error");
    20. }
    21. }