Model Binding
Model Binding
NET
Up until now, we’ve used data source controls to bind data from a database to a data control. Now we’ll learn how to
use the Entity Framework and model binding to bind data directly to a data control (GridView and DetailsView).
The Entity Framework, or just EF, is a component of ADO.NET that provides another way to work with the data in a
database.
(ADO.NET is a set of classes that expose data access services for .NET Framework programmers.)
The easiest way to create an Entity Data Model is to use the Entity Data Model Wizard. We are going to add into a
Models folder by right-clicking on our package name and adding it, then right-clicking the folder and adding the model:
Name it “Northwind”. After we create it we should see this wizard come up. We want to choose the first option.
After we have configured the wizard as shown above, we will finish and within a minute we
should see this diagram pop up.
The Entity Framework (EF) provides an interface between the database used by an application
and the objects used by an application. EF also provides for submitting changes made to those
objects to the database as recognized with the other files that are made with it.
Each entity in the Entity Data Model contains one or more scalar properties that represent the
columns in the associated table or view. A scalar property is a property that can hold a value,
such as an integer value or a string.
If any two tables that you add to an Entity Data Model are related by a foreign key, an association
is defined between the entity classes based on that relationship. We do not have to worry about
this as we are only concerned with the Customers table, but if we wanted to bind Orders and
Order Details, we would see both tables in the diagram and they would be connected like an ERD.
The main file we will be recognizing/using is the Customer class that is created. This is going to allow us to get and set
the information from the database for each column.
From here, we are going to add a CustomerDB class. This is where we will define the rest of our logic for our model
binding.
Our GridView control will display 3 pieces of data from our database (CustomerID, CompanyName, ContactName), along
with this, we will have a DetailsView control that displays the rest of the Customer’s name that’s selected in the
GridView control. The DetailsView control lets the user update or delete the selected Customer. It also lets the user
insert a new Customer, which is then displayed back in the GridView control.
I have provided the code for you in a text file, but here is a breakdown of it: