Home Application-development Entity Framework Tutorial

Entity Framework Tutorial

By Joydip Kanjilal
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introducing the ADO.NET Entity Framework
About this book

The ADO.NET Entity Framework is a new way to build the data access layer of your Windows or web applications. It's an Object Relational Mapping (ORM) technology that makes it easy to tie together the data in your database with the objects in your applications, by abstracting the object model of an application from its relational or logical model.

This clear and concise book gets you started with the Entity Framework and carefully gives you the skills to speed up your application development by constructing a better data access layer. It shows you how to get the most from the ADO.NET Entity Framework to perform CRUD operations with complex data in your applications.

This tutorial starts out with the basics of the Entity Framework, showing plenty of examples to get you started using it in your own code. You will learn how to create an Entity Data Model, and then take this further with Entity types. You will also learn about the Entity Client data provider, learn how to create statements in Entity SQL, and get to grips with ADO.NET Data Services, also known as Project Astoria.

Publication date:
October 2008
Publisher
Packt
Pages
228
ISBN
9781847195227

 

Chapter 1. Introducing the ADO.NET Entity Framework

The ADO.NET Entity Framework is an extended Object Relational Mapping (ORM) technology from Microsoft that abstracts the object model of an application from its relational or logical model. That is, it isolates the object model from the way the data is actually represented in the relational store. This framework makes the conceptual model real by using an extended entity relationship model called the ADO.NET Entity Data Model.

This chapter gives you an introduction to the ADO.NET Entity Framework and also equips you with a brief understanding of the related terminologies. We will revisit each of the Entity Framework architectural components as we progress through this book. Our journey of the ADO.NET Entity Framework has just begun!

In this chapter, we will cover the following points:

  • An overview of the ADO.NET Entity Framework

  • The ADO.NET Entity Framework Architectural Components

  • Features and benefits of the ADO.NET Entity Framework

  • Installing the ADO.NET Entity Framework

But, before we delve deep into this amazing technology from Microsoft, let's take a quick look at the prerequisites for learning the concepts covered in this book.

What You should Know

To learn the concepts covered in this book, the reader should have a basic understanding of the following:

  • Programming using ADO.NET

  • C#

  • Working with ASP.NET Web Applications

  • SQL Server

 

What You should Know


To learn the concepts covered in this book, the reader should have a basic understanding of the following:

  • Programming using ADO.NET

  • C#

  • Working with ASP.NET Web Applications

  • SQL Server

 

Looking Back


Any application has two perspectives. They are the Data Model and the Object Model. While the Data Model defines the way the data is defined and stored, the Object Model defines how the same data will be represented to the user in the presentation layer or, is exposed to the other layers of the application. The Data Model of the application usually deals with the storage and retrieval of the application's data to and from the relational store.

The relational store is used for data persistence, consistency, concurrency, and security. It contains the application's data and typically comprises of a set of tables, views, functions, procedures, and the relationships. You typically use T-SQL to query against the relational store which returns result sets that contains columns and rows of data.

However, the data returned doesn't necessarily match with the application's object oriented programming model. Usually, we don't use the data returned in the same form in which it is returned from the relational store. We write the necessary code to transform the data returned from the relational store to business objects in the data access layer of the application. Similarly, you need into write code to transform your application's business objects into a form that can be persisted into your relational store. But, what if the schema of the underlying relational store changes?

To bridge this apparent mismatch between the data and the object models, ORM tools have evolved. They are used to reduce the code required to transform your application's business objects into a form that can be persisted into the relational store and vice-versa.

 

What is ADO.NET Entity Framework?


The ADO.NET Entity Framework is a type of ORM. It is a development platform that provides a layer of abstraction on top of the relational or logical model. In doing so, it isolates the object model of the application from the way the data is actually stored in the relational store. Developers can use the ADO.NET Entity Framework to program against an object model rather than the logical or relationship model.

This level of abstraction is achieved using the Entity Data Model (EDM)—an extended Entity Relationship Model. The EDM reduces the dependency of your domain object model on the database schema of the data store in use. We will discuss more on this topic later in this chapter.

Developers can use the ADO.NET Entity Framework to work with domain specific properties such as employee name employee address, contact details, etc, without having to be concerned with how the actual data is stored and represented in the underlying data store. The framework can take care of the necessary translations to either retrieve data from your data store, or, perform inserts, updates, and deletes.

Is It Just Another ORM?

The ADO.NET Entity Framework is an extended ORM technology from Microsoft. We say it is an extended ORM because it has many additional features compared to a typical ORM. ORMs often use metadata and factory classes to retrieve data or collections of data. On the contrary, using the Entity Framework, you can easily map your data to be accessible in a relational representation in the database to objects, no matter how the mapping is implemented. You can expose different data views to your application without having to change your relational schema. In essence, this allows the applications to have their own view of the data. The applications can even reuse the same views of data amongst themselves.

The major difference between the ADO.NET Entity Framework and ORM tools is in the Entity Data Model and the former's ability to query data using strongly typed LINQ. You can even use Entity SQL, a T-SQL like query language for querying the Entity Data Model, to execute dynamic queries. In addition to what a typical ORM framework provides, the ADO.NET Entity Framework provides and supports entity inheritance, entity composition, and a flexible, loosely coupled three tiered model consisting of the conceptual model, the mapping layer, and the storage model.

The ADO.NET Entity Framework enables you to even extend the existing schema. In other words, you can extend the generated entity classes to create your own custom entity classes. You can define relationships of any kind such as one-to-one, one-to-many, and even many-to-many. So, isn't it a better ORM?

 

The ADO.NET Entity Framework Architectural Components


The ADO.NET Entity Framework is comprised of the following components:

  • The Entity Data Model

  • LINQ to Entities

  • Entity Client

  • Entity SQL

  • The Object Services Layer

The following figure illustrates the layers of the ADO.NET Entity Framework and how they are related to each other:

We will now discuss each of the components of the Entity Framework technology stack in the following sections.

 

The Entity Data Model (EDM)


The Entity Data Model, an extended entity relationship model, is the core of the ADO.NET Entity Framework.

You can generate an Entity Data Model using the EDMGen.exe command line tool, or, using the ADO.NET Entity Data Model designer—a new Visual Studio template. We will discuss how an Entity Data Model can be generated from a relational schema in the next chapter.

The following figure illustrates where exactly the Entity Data Model fits in:

The Entity Data Model abstracts the logical or the relational schema and exposes the conceptual schema of the data using a three-layered approach. It is comprised of the following layers:

  • The Conceptual Data Definition Language Layer (C-Space)

  • The Mapping Schema Definition Language Layer (C-S Space)

  • The Store Space Definition Language Layer (S-Space)

The following figure illustrates the layers of the Entity Data Model:

The Conceptual Layer or the C-Space Layer is responsible for defining the entities and their relationships. It defines your business objects and their relationships in XML files. The C-Space is modeled using CSDL and is comprised of EntityContainer, EntitySets, AssociationSets, AssociationTypes, EntityTypes, and Functions. You can query this layer using Entity SQL or ESQL (EntityConnection, EntityCommand, and EntityDataReader).

The C-S Mapping Layer is responsible for mapping the conceptual and the logical layers. That is, it maps the business objects and the relationships defined in the conceptual layer with the tables and relationships defined in the logical layer. It is a mapping system created in XML, which links or maps the Conceptual and the Logical layers. The C-S Mapping layer is modeled using MSL.

The Logical or the Storage Layer (also called the S-Space) represents the schema of the underlying database. This is comprised of tables, stored procedures, view, and functions. It is modeled using SSDL and queried using ADO.NET Data Providers. Hence, we use SQLConnection, SQLCommand, SQLDataReader, and SQLDataAdapter using T-SQL or PL-SQL if our data store is a SQL database.

Here is how a typical Entity Data Model looks:

How is the Entity Data Model Represented?

The Entity Data Model uses the following three types of XML files to represent the C-Space, C-S Space, and the S-Space respectively.

  • .CSDL (Conceptual Schema Definition Language): This represents the C-S Space and is used to map the entity types used in the conceptual model.

  • .MSL (Mapping Schema Language): This represents the C-S Space and is used to map the logical model to the conceptual model.

  • .SSDL (Store Schema Definition Language): This represents the S-Space and is used to map the schema information of the logical layer.

    Note

    If you use the ADO.NET Entity Data Model Designer tool to generate your Entity Data Model, you will have one .edmx file that contains the CSDL, MSL, and SSDL sections bundled into one single file. At runtime, the .csdl, .msl, and .ssdl files are created in the application's output directory.

These files store the metadata information as XML for each of the above layers. Here is what the CSDL section of your Entity Data Model looks like:

<!-- CSDL content -->
<edmx:ConceptualModels>
<EntityContainer Name="PayrollEntities">
<EntitySet Name="Designation" EntityType="PayrollModel.Designation" />
</EntityContainer>
<EntityType Name="Designation">
<Key>
<PropertyRef Name="DesignationID" />
</Key>
<Property Name="DesignationID" Type="Int32" Nullable= "false" />
<Property Name="DesignationName" Type="String" Nullable="false" MaxLength="50" Unicode="false" />
<NavigationProperty Name="Employee" Relationship= "PayrollModel.FK_Employee_Designation" FromRole="Designation" ToRole="Employee" />
</EntityType>
</edmx:ConceptualModels>

Here is how a typical SSDL section of the Entity Data Model looks like:

<!-- SSDL content -->
<edmx:StorageModels>
<EntityContainer Name="dbo">
<EntitySet Name="Designation" EntityType= "PayrollModel.Store.Designation" />
</EntityContainer>
<EntityType Name="Designation">
<Key>
<PropertyRef Name="DesignationID" />
</Key>
<Property Name="DesignationID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="DesignationName" Type="varchar" Nullable="false" MaxLength="50" />
</EntityType>
</Schema>
</edmx:StorageModels>

And here is the C-S maping section for you:

<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS">
<EntityContainerMapping StorageEntityContainer="dbo" CdmEntityContainer="PayrollEntities">
<EntitySetMapping Name="Designation">
<EntityTypeMapping TypeName="IsTypeOf(PayrollModel.Designation)">
<MappingFragment StoreEntitySet="Designation">
<ScalarProperty Name="DesignationID" ColumnName= "DesignationID" />
<ScalarProperty Name="DesignationName" ColumnName= "DesignationName" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
</edmx:Edmx>

Note

You can also create abstract and complex types in your Entity Data Model. You can derive from an abstract type to create sub-types, but no instance of the abstract type can be created. You can also create complex types. That is, types that don't have any identity of their own. A typical example of a complex type is the Address type.

We will skip further discussion on each of the sections of an Entity Data Model until Chapter 3.

The Object Model (O-Space)

When working with the ADO.NET Entity Framework, you will have an Object Model on top of all the Entity Data Model layers. You need to model the Object Model using .NET objects. The following figure illustrates how the Object Model fits in with the EDM layers:

The Object Model Layer contains, .NET objects, collection of .NET objects, types, properties and methods. You can use the Object Model or the O-Space Model to query your business objects, or the collections of your business objects, using LINQ to Entities or Entity SQL. The C-Space and O-Space models are actually mapped by the O-C Mapping Layer using code attributes applied to the O-space Model.

LINQ to Entities

Language Integrated Query (LINQ) is a query translation pipeline that has been introduced as part of the C# 3.0 library. It comprises a set of query operators for different data sources (LDAP, Objects, CSV, XML, Entities, SQL, etc.). It is an extension of the C# language and provides a simplified framework for accessing relational data in a strongly typed, Object Oriented manner.

LINQ to Entities is a Microsoft technology that enables you to query your business objects from within the language in a strongly typed manner. You can use LINQ to Entities, a superset of LINQ to SQL, to query data against a conceptual data model, namely, the Entity Data Model. We will learn more on LINQ and LINQ to Entities in the chapter 6.

Here is an example of a typical LINQ to Entities query:

PayrollModel.PayrollEntities ctx = new PayrollModel.PayrollEntities();
var query = from emp in ctx.Employee
select emp;
foreach (var employee in query)
Response.Write("<BR>"+employee.FirstName);

Note

LINQ to Entities rests on top of the ADO.NET Entity Framework's Object Services Layer and that the LINQ to Entities queries are internally translated to canonical query trees. This, in turn, gets converted internally to corresponding SQL queries in a form expected by your underlying database.

Entity Client

Entity Client, the gateway to entity-level queries, is the Entity Framework's counterpart of ADO.NET's SQL Client or Oracle Client that uses Entity SQL or E-SQL to query the conceptual model. You create a connection using Entity Connection, execute commands through Entity Commands, and retrieve the result sets as Entity Data Readers.

Entity SQL

Entity SQL is a data store independent derivative of T-SQL that supports entity inheritance and relationships. You can use it to query data using the conceptual schema. You can even build your own dynamic queries. These E-SQL queries are internally translated to data store dependent SQL queries. This translation, that is, the conversion of the E-SQL queries to their data store-specific query language like T-SQL, (it doesn't need to be only T-SQL, however, it is the supported one) is handled by the Entity Framework. Entity SQL or E-SQL may not be as strongly typed as LINQ is, but, you have the flexibility of executing dynamic queries using it, much like T-SQL.

Note

Strongly typed data access is one of the most striking features of LINQ. LINQ queries are checked at compile time. This is unlike SQL queries which are only detected at runtime.

But, why do you need Entity SQL when you have LINQ to Entities to query data through you Entity Data Model? You can, using Entity SQL, compose queries that are difficult to determine until the time the query is executed. On a different note, Entity SQL is a full text-based query language that you can use in much the same way as you use ADO.NET data providers.

Here is an example that shows how you can use Entity SQL to insert data in your applications.

using (EntityConnection conn = new EntityConnection("Name=PayrollEntities"))
{
try
{
conn.Open();
EntityCommand cmd = conn.CreateCommand();
cmd.CommandText = "PayrollEntities.AddNewEmployee";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("FirstName", "Joydip");
cmd.Parameters.AddWithValue("LastName", "Kanjilal");
cmd.Parameters.AddWithValue("Address", "Hyderabad");
cmd.Parameters.AddWithValue("DepartmentID", 4);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Note

To query data from the Entity Data Model, you have three choices—Entity SQL, LINQ to Entities, and Object Services.

Avoiding Complex Joins

You can use Entity SQL to avoid complex joins as you will typically be querying against a conceptual model of the data. As an example, if we want to display employee names and the department names in which they work, we would have to join the information of the Employee and the Department tables and then filter the unwanted columns to retrieve only the information that is required. Such traversals become a nightmare as you add additional tables and you therefore require more complex joins.

When you implement your Object Model using Object Oriented Programming Languages, you expose the object's relationships with other objects of its kind using properties. This is in contrast to the approach we just discussed. Hence, designing an Object Model using this approach is cumbersome. This is exactly where the ADO.NET Entity Framework fits in; it represents the conceptual and logical model of data while using grammar that is common to both.

Here is a code snippet that explains how you can use Entity SQL to avoid complex joins in your application's code. The following T-SQL query can be used to retrieve employee data split across three tables, namely, Employee, Department, and Salary.

Select Employee.FirstName, Employee.LastName, Department.DepartmentName, Salary.Basic
from Employee
INNER JOIN
Department on Department.DepartmentID = Employee.DepartmentID
INNER JOIN
Salary on Salary.EmployeeID = Employee.EmployeeID

And, here is how you will use the Entity SQL to achieve the same result:

Select FirstName, LastName, DepartmentName, Basic from EmployeeData

The Object Services Layer

Apart from querying the Conceptual Model, you might, at some point, have to work with entities such as in-memory objects or a collection of in-memory objects. To do this you need Object Services. You can use it to query data, from almost any data store, with less code. In addition to from enabling you to perform CRUD operations, the Object Services Layer provides the following additional services:

  • Change tracking

  • Lazy loading

  • Inheritance

  • Optimistic concurrency

  • Merging data

  • Identity resolution

  • Support for querying data using Entity SQL and LINQ to Entities

We will learn more about Object Services later in the book. The Object Services Layer internally uses an Object Query object for query processing. Note that the Object Services Layer supports querying data using both Entity SQL and LINQ to Entities.

Note

You can query data from the Entity Data Model either using Object Services or Entity Client. However, if you require change tracking, be aware that only Object Services provides this feature. Note that in either case, the ADO.NET Data Providers are responsible for talking to the underlying database.

Here is an example that shows how you can use Object Services to retrieve data.

using (ObjectContext ctx = new ObjectContext("Name=PayrollEntities"))
{
var query = from employee in ctx.CreateQuery<PayrollModel.Employee>("PayrollEntities.
Employee") select employee;
foreach (PayrollModel.Employee emp in query)
{
Response.Write("<BR>" + emp.FirstName);
}
}

ADO.NET Entity Framework—Features and Benefits at a Glance

Here is a quick look at some of the features and benefits of the ADO.NET Entity Framework:

  • Increased level of abstraction.

  • An extensible and flexible provider model.

  • Seamless querying of data using Entity SQL and LINQ.

  • A flexible schema for storing the mapping information.

  • Reduction to the amount of KLOC needed to write data access code in your applications.

  • Provides a layer of abstraction on top of any data store as long as an implementation for the underlying data store is provided.

  • A powerful Object Services Layer.

  • A full text-based query language.

  • Support for a conceptual data model of an application.

    Note

    KLOC refers to Kilo Lines of Code, a unit of measuring the amount of source code in your programs.

 

Installing the Prerequisites


To run the programs given in this book, you should have the following elements installed on your system:

  • Visual Studio.NET 2008 Professional

  • SQL Server 2005 or higher

  • Microsoft .NET Framework 3.5 SP1

  • ADO.NET Entity Framework Beta 3 or higher

  • ADO.NET Entity Framework Tools December 2007 CTP or higher

Installing the ADO.NET Entity Framework and Its Tools

Before you proceed with installing EF Beta 3 and its tools, make sure that you have installed Visual Studio.NET 2008 Professional and SQL Server 2005 on your system. I will skip the discussion on installing Visual Studio 2008 Professional and SQL Server 2005 at this time.

Downloading the Software

Let us take a look at the necessary software that you need to download in order to work with the ADO.NET Entity Framework.

Installing the Software

Now that the required software has been downloaded, we will now install each one individually.

Double-click on the ADO.NET Entity Framework Setup file. The following installation wizard window will appear:

Now, click on Next.

Here is how the next screen looks like:

In the above window that appears, check the checkbox and click on Install.

The installation procedure starts and when done, the following screen appears:

Click on Finish to complete the installation process.

Now that you have installed the ADO.NET Entity Framework successfully on your system, the next step is to install the ADO.NET Entity Framework Tools CTP. But before you do that, you need to install the Visual Studio.NET 2008 patch update.

Double-click on the Visual Studio.NET patch update setup file that you downloaded earlier. The following window appears:

Now, click on Next.

The following window appears:

Check the check box to agree and accept the license terms and click on Next to start the installation process.

Once the installation is complete, the following window appears:

Click on Finish to complete the installation process.

Now, we need to install the ADO.NET Entity Framework Tools CTP. To do this, double-click on the ADO.NET Entity Framework December 2007 Tools CTP you downloaded earlier. The following screen appears:

Click on Next. The following window appears:

Now, check the check box to accept the license terms and click on Next. The following window will appear:

Click on Install to start the installation process. Once the installation is complete, the following window is displayed:

Clink on Finish to complete the installation process.

We will now install Microsoft .NET Framework 3.5 SP1. It contains many additional features and most importantly, we need it to work with the Entity Data Source control. We will discuss this control in the next chapter.

To install Microsoft .NET Framework 3.5 SP1 on your system, double-click on the setup file you downloaded earlier. The following screenshot shows the window that will appear:

Select the radio button to accept the terms of the license agreement and click on Install to start the installation process.

Once the installation process is complete, the following window is displayed:

Click on Exit to complete the installation process. You are done!

Having installed these prerequisites, we will now design our sample database. We will use this database throughout this book. We will assign the name Payroll to our design database. The next section discusses the design of this sample database.

 

Designing the Payroll Database


In this section, we will design our Payroll database, which we will use throughout this book. This database will comprised of the following five tables:

  • Employee

  • Department

  • Designation

  • Salary

  • Provident Fund

Here is the script for creating these tables.

CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[LastName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Address] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Phone] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[DepartmentID] [int] NOT NULL,
[JoiningDate] [datetime] NOT NULL,
[LeavingDate] [datetime] NULL,
[DesignationID] [int] NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[EmployeeID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Department](
[DepartmentID] [bigint] NOT NULL,
[DepartmentName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[DepartmentHead] [bigint] NOT NULL,
CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED
(
[DepartmentID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Designation](
[DesignationID] [bigint] NOT NULL,
[DesignationName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
CONSTRAINT [PK_Designation] PRIMARY KEY CLUSTERED
(
[DesignationID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Salary](
[SalaryID] [bigint] NOT NULL,
[EmployeeID] [bigint] NOT NULL,
[Basic] [money] NOT NULL,
[Allowance] [money] NOT NULL,
[PFID] [bigint] NULL,
[Tax] [money] NOT NULL,
[GrossSalary] [money] NOT NULL,
[NetSalary] [money] NOT NULL,
CONSTRAINT [PK_Salary] PRIMARY KEY CLUSTERED
(
[SalaryID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[ProvidentFund](
[PFID] [bigint] NOT NULL,
[PFAmount] [money] NOT NULL,
CONSTRAINT [PK_ProvidentFund] PRIMARY KEY CLUSTERED
(
[PFID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Here is how the database diagram for our Payroll database looks:

We will create some stored procedures now that we will use to insert, update, and delete data from the tables we just created. Here is a list of the stored procedures that we will create for our Payroll database:

  • Employee_Insert

  • Employee_Update

  • Employee_Delete

  • Department_Insert

  • Department_Update

  • Department_Delete

  • Designation_Insert

  • Designation_Update

  • Designation_Delete

  • ProvidentFund_Insert

  • ProvidentFund_Update

  • ProvidentFund_Delete

  • Salary_Insert

  • Salary_Update

  • Salary_Delete

Here is the script for these procedures.

Create Procedure Employee_Insert
As
@FirstName varchar(50), @LastName varchar(50), @Address varchar(50), @Phone varchar(50), @DepartmentID int, @DesignationID int,
@JoiningDate datetime, @LeavingDate datetime
as
Insert into Employee(DepartmentID, DesignationID, JoiningDate, LeavingDate) values (@DepartmentID, @DesignationID, @JoiningDate, @LeavingDate)
Go
Create Procedure Employee_Update
@EmployeeID int, @FirstName varchar(50), @LastName varchar(50), @Address varchar(50), @Phone varchar(50), @DepartmentID int, @DesignationID int
as
Update Employee Set DepartmentID = @DepartmentID, DesignationID = @DesignationID Where Employee.EmployeeID = @EmployeeID
Go
Create Procedure Employee_Delete
@EmployeeID int
as
Delete from Employee where Employee.EmployeeID = @EmployeeID
Go
Create Procedure Department_Insert
@DepartmentName varchar(50)
as
Insert into Department (DepartmentName) values (@DepartmentName)
Go
Create Procedure Department_Update
@DepartmentID int,@DepartmentName varchar(50)
as
Update Department Set DepartmentName = @DepartmentName where DepartmentID = @DepartmentID
Go
Create Procedure Department_Delete
@DepartmentID int
as
Delete from Department where DepartmentID = @DepartmentID
Go
Create Procedure Designation_Insert
@DesignationName varchar(50)
as
Insert into Designation (DesignationName) values (@DesignationName)
Go
Create Procedure Designation_Update
@DesignationID int, @DesignationName varchar(50)
as
Update Designation Set DesignationName = @DesignationName where DesignationID=@DesignationID
Go
Create Procedure Designation_Delete
@DesignationID int
as
Delete from Designation where DesignationID=@DesignationID
Go
Create Procedure ProvidentFund_Insert
@EmployeeID int, @PFAmount money
as
Insert into ProvidentFund (EmployeeID, PFAmount) values (@EmployeeID, @PFAmount)
Go
Create Procedure ProvidentFund_Update
@PFID int, @EmployeeID int, @PFAmount money
as
Update ProvidentFund set EmployeeID = @EmployeeID, PFAmount = @PFAmount where PFID = @PFID
Go
Create Procedure ProvidentFund_Delete
@PFID int
as
Delete from ProvidentFund where PFID = @PFID
Go
Create Procedure Salary_Insert
@EmployeeID int, @PFID int, @Basic money, @Allowance money, @Tax money, @GrossSalary money, @NetSalary money
as
Insert into Salary(EmployeeID, PFID, Basic, Allowance, Tax, GrossSalary, NetSalary) values (@EmployeeID, @PFID, @Basic, @Allowance, @Tax, @GrossSalary, @NetSalary)
Go
Create Procedure Salary_Update
@SalaryID int, @EmployeeID int, @PFID int, @Basic money, @Allowance money, @Tax money, @GrossSalary money, @NetSalary money
as
Update Salary set EmployeeID = @EmployeeID, PFID = @PFID, Basic = @Basic, Allowance = @Allowance, Tax = @Tax, GrossSalary = @GrossSalary, NetSalary = @NetSalary where SalaryID = @SalaryID
Go
Create Procedure Salary_Delete
@SalaryID int
as
Delete from Salary where SalaryID = @SalaryID

We will add more tables and stored procedures to our Payroll database as necessary in the chapters to follow.

 

Summary


The ADO.NET Entity Framework mainly addressees how easily you can persist and query your data with many of added services. You can use the ADO.NET Entity Framework to focus on the object model rather than the logical model. In other words, you can add a level of abstraction on top of your relational store.

In this chapter, we have had a look at what this framework is, its architecture, advantages, and how it differs from LINQ to SQL (formerly called DLINQ). In the next chapter, we will learn how to get started with the ADO.NET Entity Framework.

 

Glossary


Entity: This is the core concept in the Entity Framework. An Entity essentially models individual objects, like, employees, customers, etc. It is something that is uniquely definable, distinctly identifiable, and contains information pertaining to the entity.

Relational or Logical Model: A relational or logical model depicts the logical view of data that comprises of the normalized entities and their inter-relationships in a database.

Object Model: An Object Model may be defined as a collection of the objects, members, and properties of a class and the relationships between them that illustrates the structure of a system. An Object Model of a system is centered on the three basic properties of Object Oriented Programming—encapsulation, abstraction, and inheritance.

The Entity Data Model (EDM) is an implementation for the Entity Relationship model (commonly called the E-R model). It depicts the entities and their relationships. The EDM is a view of the data store that your application will use.

About the Author
  • Joydip Kanjilal

    Joydip Kanjilal is a Microsoft Most Valuable Professional in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP (Most Valuable Professional) award at ASP.Net for 2007, 2008, 2009, 2010, 2011, and 2012. He is currently working as a Chief Software Architect at a reputed software company in Hyderabad.

    Joydip has almost 20 years of industry experience in IT, with more than 14 years in Microsoft .NET and its related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

    He is the author of several books and more than 250 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.NET.

    Joydip has authored the following books:-

    • ASP.NET Web API (Packt Publishing)
    • Visual Studio Six in One (Wrox Publishers)
    • ASP.NET 4.0 Programming (Mc-Graw Hill Publishing)
    • Entity Framework Tutorial (Packt Publishing)
    • Pro Sync Framework (APRESS)
    • Sams Teach Yourself ASP.NET Ajax in 24 Hours (Sams Publishing)
    • ASP.NET Data Presentation Controls Essentials (Packt Publishing)

    Joydip has also reviewed more than a dozen books till date. He was a speaker a speaker at the reputed Spark IT 2010 event and at the reputed Dr. Dobb’s Conference 2014 in Bangalore. He's also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He blogs these days at: http://www.infoworld.com/blog/microsoft-coder

    Browse publications by this author
Entity Framework Tutorial
Unlock this book and the full library FREE for 7 days
Start now