다음을 통해 공유


DataGridView/Entity Framework common operations (Part 1)

Introduction

Learn how use Entity Framework in a Windows form project with the following behavior; immediate updates when leaving a DataGridViewTextBoxColum or a DataGridViewComboBox column, column sorting which is not supported out of the box with Entity Framework, filtering data, finding and positioning data. Adding and deleting data will be covered in the next part of the series with hooks already in place to move forward for adding/deleting data.

Since the majority of data solutions require a relational setup rather than a single table the example here is based on four tables to present basic information on a customer while more details could be added such as more details on a customer or contact this information usually is placed into a modal form presented by double clicking a row in the DataGridView or clicking a DataGridViewButtonColumn.

The series continues here in part 2.

Reverse Engineering

Reverse engineering is the process of scaffolding entity type classes and a DbContext class based on a database schema. In a project select add new item, data, ADO.NET Entity data model, code first from database then follow the steps to the end to create a DbContext and entity type classes (models) or install Entity Framework 6 Power Tools Community Edition by ErikJ using tools, extensions and updates from within Visual Studio. Once installed right click on a project to create the complete structure. Scaffolding can also be done through the power shell interface in Visual Studio which take a good deal of knowledge to get it right.

Data relations

There are four tables from a SQL-Server database used to present customer data in a DataGridView, a customer table, a contact table, a contact type and a country table where the parent table, customer contains primary keys for each of the child tables.

DbContext

The DbContext class more tables than necessary for this article for future lessons. There are also several custom methods which provide access to the ChangeTracker to determine changes to the data. There is a caveat, in Entity Framework Core part of this code currently has parts missing while developers have asked for this functionality to be accessible at this time it’s not. The method name is GetPrimaryKeyValue. Then there is DbEntityEntry which is has been replaced with EntityEntry.

Custom customer class

Since the customer class does not contain all text to display and custom class is required which hold all text to display along with primary and foreign keys to read necessary information from other models/tables e.g. two DataGridViewComboBox columns, one for country and one for contact type.

INotifyPropertyChanged

Implementing INotifyPropertyChanged Interface is considered the glue to allowing form controls such as a DataGridView to know when a underlying value has changed which coupled with the sortable BindingList (see below) allows immediate updates to be done using ListChanged event of the BindingList.

DataGridView columns setup

Each property to be displayed in the DataGridView were created at design time to specify the column type and DataPropertyName which indicates the property within the customer list to display.

Projects

A class project contains Entity Framework DbContext, models and custom classes which are consumed by a front-end Windows form project. By separating the two, data and user interface allows the backend class project to be used by other front-end projects. A business layer is excluded for this article which can easily be added.

Both projects segment various elements into folders rather than having everything at the root of the project. This is nothing more than an organization thing for developers. 

BindingSource

A BindingSource class provides flexibility over simply setting a list as the DataSource for a DataGridView for navigating data in the DataGridView either visually by means of a BindingNavigator or move method of the BindingSource. Using a BindingSource allows a developer to access data without touching the DataGridView, instead for instance the Current property of the BindingSource points to the current row of the DataGridView.

The only true need for physically touching the DataGridView is for DataGridView events e.g. DataError event. DataError is an event which is triggered by a run-time exception, for instance when (and this is a common error) not setting up a DataGridViewComboBox column properties correctly to shows a value for the current row in the DataGridView. In the code provided this event has been setup to only do something while coding in Visual Studio, not outside the IDE.

DataGridView sorting

Unlike working with a DataSet/DataTable or DataTable as the DataSource of a DataGridView which knows how to sort by clicking a column header using a list the DataGridView does not understand how to sort. For this a custom BindingList is used which as with a standard BindingList is strong typed. Since the BindingList is not enough by itself it becomes the DataSource of the BindingSource and the BindingSource becomes the DataSource of the DataGridView which then provides column click sorting.

The following BindingList provides sorting strongly typed to CustomerEntity.

Language extension methods

Throughout code in the form project language extensions are used to keep well working/lengthy code out of sight coupled with making code in the form easier to read. All language extensions may be discarded and place their code into the form which will immediately turn into hard to read code yet works no different than as presented as extension methods.

Special form controls

A search input of type ToolStripTextBox is used placed with limited real estate which prohibits showing what is expected which lead to a custom ToolStripTextBox which provides a placeholder when there is not text entered to explain which is expected. For a normal TextBox or ComboBox there is a language extension method to provide placeholders as the ToolStripTextBox needs to be implemented differently than a TextBox or ComboBox.

Code walk-through 

In the next part of the series a complete walk-through will be done on this page.

Summary

High level information has been provided to implementing immediate updates, filtering and searching using Entity Framework 6 in a Windows form project spanning a form project and a class project.

See also

VB.NET Entity Framework: Wiki portal

Source code

The code is part of a Visual Studio solution with other code samples found in this GitHub repository.

  • Back end class project (which includes a data script to create the database and populate tables)
    • Change the connection string in app.config to match your server name e.g. .\SQLEXPRESS
    • Make the same connection string change in app.config of the front end project also.
  • Front end form project