Creating Entity Framework Driven ASP.NET Application
I have already written several posts on the Entity Framework where I described the power of this particular ORM tool. I also mentioned the book on the Entity Framework written by a Microsoft MVP - Joydip Kanjila. This time I will publish an extract from the book that shows how you can build ASP.NET application by using the Entity Framework and the EntityDataSource control. It can also give a glimpse of the Entity Framework is, if you have no experience in it.
The tutorial covers the following topics:
- Creating the Entity Data Model by using a graphical utility built-in Visual Studio 2008 SP1
- Creating the Entity Data Model by using a command line utility
- Using the EntityDataSource ASP.NET control
- Displaying the data in a GridView
This tutorial uses a particular database, but in fact you can use any database you already have.
Creating an Entity Data Model.
You can create the ADO.NET Entity Data Model in one of the two ways:
- Use the ADO.NET Entity Data Model Designer
- Use the command line Entity Data Model Designer called EdmGen.exe
We will first take a look at how we can design an Entity Data Model using the ADO.NET Entity Data Model Designer which is a Visual Studio wizard that is enabled after you install ADO.NET Entity Framework and its tools. It provides a graphical interface that you can use to generate an Entity Data Model.
Creating the Payroll Entity Data Model using the ADO.NET Entity Data Model Designer
Here are the tables of the 'Payroll' database that we will use to generate the data model:
To create an entity data model using the ADO.NET Entity Data Model Designer, follow these simple steps:
Note that you can also use the Empty model template to create the Entity Data Model yourself.
If you select the Empty Data Model template and click on next, the following screen appears:
As you can see from the above figure, you can use this template to create the Entity Data Model yourself. You can create the Entity Types and their relationships manually by dragging items from the toolbox. We will not use this template in our discussion here. So, let's get to the next step.
We will use a dot to specify the database server name. This implies that we will be using the database server of the localhost, which is the current system in use.
Note the Entity Connection String generated automatically. This connection string will be saved in the ConnectionStrings section of your application's web.config file. This is how it will look like:
<add name="PayrollEntities" connectionString="metadata=res:// *;
provider=System.Data.SqlClient;provider connection string="
Data Source=.;Initial Catalog=Payroll;User ID=sa;Password=joydip1@3;
MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
Here is the output displayed in the Output Window while the Entity Data Model is being generated:
Your Entity Data Model has been generated and saved in a file named PayrollModel.edmx. We are done creating our first Entity Data Model using the ADO.NET Entity Data Model Designer tool.
When you open the Payroll Entity Data Model that we just created in the designer view, it will appear as shown in the following figure:
Note how the Entity Types in the above model are related to one another. These relationships have been generated automatically by the Entity Data Model Designer based on the relationships between the tables of the Payroll database.
In the next section, we will learn how we can create an Entity Data Model using the EdmGen.exe command line tool.
Creating the Payroll Data Model Using the EdmGen Tool
We will now take a look at how to create a data model using the Entity Data Model generation tool called EdmGen.
The EdmGen.exe command line tool can be used to do one or more of the following:
- Generate the .cdsl, .msl, and .ssdl files as part of the Entity Data Model
- Generate object classes from a .csdl file
- Validate an Entity Data Model
The EdmGen.exe command line tool generates the Entity Data Model as a set of three files: .csdl, .msl, and .ssdl. If you have used the ADO.NET Entity Data Model Designer to generate your Entity Data Model, the .edmx file generated will contain the CSDL, MSL, and the SSDL sections. You will have a single .edmx file that bundles all of these sections into it. On the other hand, if you use the EdmGen.exe tool to generate the Entity Data Model, you would find three distinctly separate files with .csdl, .msl or .ssdl extensions.
Here is a list of the major options of the EdmGen.exe command line tool:
Use this option to display help on all the possible options of this tool. The short form is /?
Use this option to generate code using C# language
Use this option to generate code using VB language
Use this option to specify the name of the ADO.NET data provider that you would like to use.
Use this option to specify the connection string to be used to connect to the database
Use this option to specify the name of the namespace
Use this option to generate your CSDL, MSL, and SSDL objects from the database schema
Use this option to generate your entity classes from a given CSDL file
Use this option to generate MSL, CSDL, and Entity Classes from a given SSDL file
Use this option to validate the CSDL, SSDL, and MSL files
Use this option to generate mapping views from the CSDL, SSDL, and MSL files
Note that you basically need to pass the connection string, specify the mode, and also the project name of the artifact files (.csdl, .msl, and the .ssdl files) to be created. To create the Entity Data Model for our database, open a command window and type in the following:
edmgen /mode:fullgeneration /c:"Data Source=.;Initial Catalog=Payroll;User ID=sa;
This will create a full ADO.NET Entity Data Model for our database. The output is shown in the following figure:
You can now see the list of the files that have been generated:
You can validate the Payroll Entity Data Model that was just created, using the ValidateArtifacts option of the EdmGen command line tool as shown below:
EdmGen /mode:ValidateArtifacts /inssdl:Payroll.ssdl /inmsl:Payroll.msl /incsdl:Payroll.csdl
When you execute the above command, the output will be similar to what is shown in the following figure:
As you can see in the previous figure, there are no warnings or errors displayed. So, our Entity Data Model is perfect.
The section that follows discusses the new Entity Data Source control which was introduced as part of the Visual Studio.NET 2008 SP1 release.
The ADO.NET Entity Data Source Control
Data controls are those that can be bound to data from external data sources. These data sources may include databases, XML files, or even flat files. ASP.NET 2.0 introduced some data source controls with a powerful data binding technique so the need for writing lengthy code for binding data to data controls has been eliminated.
In ASP.NET, the term Data Binding implies binding the controls to data retrieved from a data source and providing a read or write connectivity between these controls and the data that they are bound to.
The Entity Data Source control is an example of a data control that is included as part of the Visual Studio 2008 SP1 release and can be used to bind data retrieved from an Entity Data Model to the data bound controls of ASP.NET. If you have installed Visual Studio 2008 SP1, you can see the EntityDataSource control listed in the Data section of your toolbox.
If you cannot locate the EntityDataSource control in the toolbox, follow these steps:
- Right-click on the Toolbox and select the Choose Items option as shown in the following figure:
- From the list of the components displayed, scroll down to locate the EntityDataSource in the .NET Framework Components tab. Refer to the following figure:
- Now, check the checkbox next to the EntityDataSource component and click on OK.
The ADO.NET Entity Data Source control is now added to your toolbox as shown in the following figure:
If the EntityDataSource component is not listed in the list of the componentsdisplayed in the Choose Toolbox Items window, you will have to add it manually. To do this, click on the Browse button in the Choose Toolbox Items window, locate theSystem.Web.Entity.dll in the folder in your system where Microsoft .NET Framework 3.5 has been installed and click on OK.
Implementing Our First Application Using the Entity Framework
In this section, we will learn how to use the Entity Data Model and the Entity Data Source Control to implement our first program using the Entity Framework. We will use a GridView control to display bound data.
Refer to the solution we created earlier using the Entity Data Model Designer. Now, follow these steps:
- Drag and drop an Entity Data Source control from the toolbox onto your Default.aspx web form.
- Now, click on the Configure Data Source option to specify the data source. Refer to the following figure:
- Specify the Connection String and DefaultContainerName and then click on Next.
- Specify the fields you would want to retrieve from the database table and click on Finish when done.
- Now, drag and drop a GridView control from the toolbox onto the Default.aspx web form as seen in the following figure:
- Next, use the Choose Data Source option of the GridView control to associate its data source with the Entity Data Source control we created earlier. Refer to the following figure:
Here is how the markup code of the GridView control looks with its templates defined. Note how the DataSourceID of the GridView control has been associated with the Entity Data Source control we created earlier.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID"
DataSourceID="SqlDataSource1" BorderColor="Black" BorderStyle="Solid" Width="400px">
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" ReadOnly="True"
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
We are done! When you execute the application, your output should be similar to what is shown in the following figure:
|Learn to build a better data access layer with the ADO.NET Entity Framework and ADO.NET Data Services
About the Author
Joydip Kanjilal is a Microsoft MVP in ASP.NET. He has over 12 years of industry experience in IT with more than 6 years in Microsoft .NET and its related technologies. He has authored many articles for some of the most reputable sites like,www.asptoday.com, www.devx.com, www.aspalliance.com, www.aspnetpro.com, www.sql-server-performance.com, www.sswug.com, etc. Several of these articles have been featured at www.asp.net—Microsoft's Official Site on ASP.NET. Joydip was also a community credit winner at www.community-credit.com a number of times.
He is currently working as a Senior Consultant in a reputable company in Hyderabad, INDIA. He has years of experience in designing and architecting solutions for various domains. His technical strengths include C, C++, VC++, Java, C#, Microsoft .NET, Ajax, Design Patterns, SQL Server, Operating Systems, and Computer Architecture. Joydip blogs at http://aspadvice.com/blogs/joydip and spends most of his time reading books, blogs, and writing books and articles. His hobbies include watching cricket and soccer and playing chess.