Entity Framework Tutorial Second Edition - Sample Chapter
Entity Framework Tutorial Second Edition - Sample Chapter
"Community
Experience
Distilled"
Joydip Kanjilal
C o m m u n i t y
D i s t i l l e d
E x p e r i e n c e
Joydip Kanjilal
in ASP.NET. He is a speaker and author of several books and articles. He has over
18 years of industry experience in IT, with more than 12 years in Microsoft .NET
and its related technologies. Joydip is currently working as a Principal Architect
at SenecaGlobal IT Services Private Limited, Hyderabad. He has been selected as
an MSDN Featured Developer of the Fortnight (MSDN) a number of times and has
also been a Community Credit Winner at www.community-credit.com several times.
He has authored the following books:
ASP.NET Web API: Build RESTful Web Applications and Services on the .NET
Framework by Packt Publishing
He has authored more than 250 articles for some of the most reputable sites,
such as www.msdn.microsoft.com, www.code-magazine.com, www.asptoday.com,
www.devx.com, www.ddj.com, www.aspalliance.com, www.aspnetpro.com,
www.sql-server-performance.com, www.sswug.com, and so on. A lot of these
articles have been selected at www.asp.net, Microsoft's official site on ASP.NET.
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, WCF, web-based APIs, REST, SOA, design patterns, SQL Server, operating
systems, and computer architecture.
http://aspadvice.com/blogs/joydip
http://www.infoworld.com/blog/microsoft-coder
Website: www.joydipkanjilal.com
Twitter: https://twitter.com/joydipkanjilal
Facebook: https://www.facebook.com/joydipkanjilal
LinkedIn: http://in.linkedin.com/in/joydipkanjilal
Preface
The ADO.NET Entity Framework, the next generation of Microsoft's data access
technology, is an extended Object Relational Mapping (ORM) technology that makes
it easy to tie together the data in your database with the objects in your applications.
This is done by abstracting the object model of an application from its relational or
logical model. It is an extended ORM in the sense that it provides many additional
features that a traditional ORM does not.
This book is a clear and concise guide to the ADO.NET Entity Framework. Packed
with plentiful code examples, this book helps you learn the ADO.NET Entity
Framework and ADO.NET Data Services and build a better data access layer for
your application.
The intent of writing this book is updating you to the latest trends and developments
as far as Entity Framework is concerned.
Preface
Getting Started
In the previous chapter, we took a look at Entity Framework, including its
architecture and its features. We also had a look at the new and enhanced
features in Entity Framework 7. Note that Entity Framework 6.0 ships with
Visual Studio 2013, but you can also install it via NuGet if needed. Also, Entity
Framework 7 is yet to be released.
In this chapter, we will design our Security database, create an Entity Data
Model (EDM) on top of it, and then use the EntityDataSource control to bind
data exposed by the EDM to a GridView control.
The DataSource controls are those that are used to connect to a data source and
then retrieve data from those data sources. If you use DataSource controls, the
need of writing tedious code to perform Create, Read, Update, Delete (CRUD)
operations on data-based controls is eliminated. The EntityDataSource control
is a DataSource control that can connect to the data exposed by the EDM to
perform CRUD operations.
In this chapter, we will cover the following points:
[ 31 ]
Getting Started
[ 32 ]
Chapter 2
Object Services
LINQ to
Entities
Object Query
Entity SQL
Entity SQL
Database
As you can see in this diagram, our application needs to interact with the CSDL
layer. The SSDL layer will connect to the database (the Security database in
our example), and the mapping layer will map these two layers so that they can
communicate.
The Security database comprises of a list of the following tables:
[ 33 ]
Getting Started
Controls: This table contains an entry per control (note that each control
is an object).
You can create the Entity Data Model in one of two ways:
The first approach is preferred to the second. However, as we move through the
chapters of the book, we will explore how we can follow the code-first approach to
implement the model for our application that uses Entity Framework.
We will first take a look at how we can design an EDM using the ADO.NET Entity
Data Model Designer.
[ 34 ]
Chapter 2
[ 35 ]
Getting Started
5. Select Generate from database from Entity Data Model Wizard, as shown in
the following screenshot:
Note that you can also use the Empty model template to
create the EDM yourself.
[ 36 ]
Chapter 2
If you select the Empty model template and click on Next, the following
screen appears:
As you can see from the previous screenshot, you can use this template to
create the EDM 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.
6. Click on Next in the Entity Data Model Wizard window shown earlier.
7. The modal dialog box will now appear and prompt you to choose
your connection.
[ 37 ]
Getting Started
8. Click on New Connection. Now you will need to specify the connection
properties and parameters for the database to connect to. In our example,
the database is Security.
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. You can also specify the server name here if your database
resides on a different system. If your database resides on a different
server, you need to specify the server name here.
9. After you specify the necessary user name, password, and server name, you
can test your connection using the Test Connection button. When you do so,
the message Test connection succeeded gets displayed in the message box,
as shown in the following screenshot:
[ 38 ]
Chapter 2
10. Now, click on Next and specify the database objects you would like to
have in your model from the Choose Your Database Objects and Settings
window that is shown next:
[ 39 ]
Getting Started
We will select all the tables of the Security database now. Refer to the
following screenshot:
11. Lastly, click on Finish to generate the EDM for the Security database.
Your EDM has been generated and saved in a file named SecurityDB.edmx. We are
done creating our first EDM using the ADO.NET Entity Data Model Designer tool.
[ 40 ]
Chapter 2
When you open SecurityDB.edmx that we just created in the designer view, it will
appear as shown in the following image:
In the next section, we will learn to create an EDM using the EdmGen.exe commandline tool.
Generate the .cdsl, .msl, and .ssdl files as part of the EDM
Validate an EDM
[ 41 ]
Getting Started
The EdmGen.exe command-line tool generates the EDM as a set of three files: .csdl,
.msl, and .ssdl. If you have used the ADO.NET Entity Data Model Designer to
generate your EDM, 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 EDM, you will
find three separate files with .csdl, .msl, or .ssdl extensions.
Here is a list of the major options of the EdmGen.exe command-line tool:
Option
Description
/help
/language:CSharp
/language:VB
/provider:<string>
/connectionstring:<connection
string>
/namespace:<string>
/mode:FullGeneration
/mode:EntityClassGeneration
/mode:FromSsdlGeneration
/mode:ValidateArtifacts
/mode:ViewGeneration
/entitycontainer:<string>
/project:<string>
[ 42 ]
Chapter 2
Note that you need to pass the connection string, and specify the mode and the
project name of the artifact files (the .csdl, .msl, and .ssdl files) to be created.
To create the EDM for our database, open a Visual Studio command window
and type in the following:
edmgen /mode:fullgeneration /c:"Data Source=.;Initial
Catalog=SecurityDB;User ID=sa;Password=sa1@3;" /p:SecurityDB
This will create a full Entity Data Model for our database. The output is shown in the
following screenshot:
You can also validate the SecurityDB model that was just created, using the
ValidateArtifacts option of the EdmGen command-line tool, as follows:
EdmGen /mode:ValidateArtifacts /inssdl:SecurityDB.ssdl
/inmsl:SecurityDB.msl /incsdl:SecurityDB.csdl
When you execute the preceding command, the output will be similar to what is
shown in the previous screenshot.
As you can see in the previous screenshot, there are no warnings or errors displayed.
So, our EDM is perfect.
The section that follows discusses the DataSource controls included in ASP.NET
and also the new EntityDataSource control, which was first introduced as part of
the Visual Studio.NET 2008 SP1 release. Note that the EntityDataSource control is
included as part of Visual Studio 2010 and onward.
[ 43 ]
Getting Started
A DataSource control acts like a layer in between your data source and the data
bound control. Data bound controls can be any control that actually interacts with
the end user while consuming the data services provided by the DataSource control
to which it is bound. It defines certain methods and properties that perform dataspecific operations like insert, delete, update, and select over the data exposed by
the DataSource control while at the same time abstracting the data source.
In the sections that follow, we will discuss these controls with special emphasis on
the EntityDataSource control.
[ 44 ]
Chapter 2
[ 45 ]
Getting Started
[ 46 ]
Chapter 2
Let's first have the environment ready. I will run you through the steps to download
and install Entity Framework 6 now.
In the Solution Explorer, right-click on the project and select EntityFramework from
the list of NuGet packages, as shown in the following screenshot:
[ 47 ]
Getting Started
Once Entity Framework 6 has been downloaded, click on Accept to start the
installation. After Entity Framework 6 has been successfully installed and the
necessary changes applied to your project, you are ready to start writing your
first application that makes use of this framework.
[ 48 ]
Chapter 2
Refer to the solution we created earlier using the Entity Data Model Designer. Now
follow these steps:
1. Drag and drop an EntityDataSource control from the toolbox onto your
Default.aspx web form:
[ 49 ]
Getting Started
2. Now click on the Configure Data Source... option to specify the data source.
Refer to the following screenshot:
[ 50 ]
Chapter 2
4. Specify the fields you want to retrieve from the database table, and click on
Finish when done:
5. Now drag and drop a GridView control from the toolbox onto the
Default.aspx web form.
[ 51 ]
Getting Started
6. Next, use the Choose Data Source option of the GridView control to associate
its data source with the EntityDataSource control we created earlier. Refer to
the following screenshot:
This 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 EntityDataSource control we created earlier.
EntityDataSource control we created earlier.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataSourceID="EntityDataSource1">
<Columns>
<asp:BoundField DataField="UserAuthenticationID"
HeaderText="UserAuthenticationID" ReadOnly="True"
SortExpression="UserAuthenticationID" />
<asp:BoundField
DataField="UserAuthenticationTypeID"
HeaderText="UserAuthenticationTypeID"
ReadOnly="True"
SortExpression="UserAuthenticationTypeID" />
<asp:BoundField DataField="UserID"
HeaderText="UserID" ReadOnly="True"
SortExpression="UserID" />
<asp:BoundField DataField="UserName"
HeaderText="UserName" ReadOnly="True"
SortExpression="UserName" />
</Columns>
</asp:GridView>
[ 52 ]
Chapter 2
The markup code of the EntityDataSource control looks like the following:
<asp:EntityDataSource ID="EntityDataSource1" runat="server"
ConnectionString="name=SecurityDBEntities"
DefaultContainerName="SecurityDBEntities" EnableFlattening="False"
EntitySetName="UserAuthentications"
EntityTypeFilter="UserAuthentication"
Select="it.[UserAuthenticationID], it.[UserAuthenticationTypeID],
it.[UserID], it.[UserName]">
</asp:EntityDataSource>
This is what the complete markup code of the Default.aspx web page looks like:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:EntityDataSource ID="EntityDataSource1"
runat="server" ConnectionString="name=SecurityDBEntities"
DefaultContainerName="SecurityDBEntities"
EnableFlattening="False"
EntitySetName="UserAuthentications"
EntityTypeFilter="UserAuthentication"
Select="it.[UserAuthenticationID],
it.[UserAuthenticationTypeID],
it.[UserID], it.[UserName]">
</asp:EntityDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="EntityDataSource1">
<Columns>
<asp:BoundField DataField="UserAuthenticationID"
HeaderText="UserAuthenticationID" ReadOnly="True"
SortExpression="UserAuthenticationID" />
<asp:BoundField
DataField="UserAuthenticationTypeID"
HeaderText="UserAuthenticationTypeID"
ReadOnly="True"
SortExpression="UserAuthenticationTypeID" />
<asp:BoundField DataField="UserID"
HeaderText="UserID" ReadOnly="True"
SortExpression="UserID" />
[ 53 ]
Getting Started
<asp:BoundField DataField="UserName"
HeaderText="UserName" ReadOnly="True"
SortExpression="UserName" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
When you execute the application, your output should be similar to what is shown
in the following image:
Data exposed by the Entity Data Model is displayed in the GridView control
Summary
In this chapter, we discussed how we can get started with Entity Framework.
You learned how to create an EDM and use it along with the EntityDataSource
control, to bind data to a GridView data control. In this chapter, we created
the UserAuthentication database and an EDM that exposed this database.
We also explored the EntityDataSource control and used it to bind data in
our first application that leverages Entity Framework 6.
In the next chapter, we will continue to explore the EDM including each of its
sections and will learn how they are related to each other.
[ 54 ]
www.PacktPub.com
Stay Connected: