Home Programming Entity Framework Tutorial (Update) - Second Edition

Entity Framework Tutorial (Update) - Second Edition

By Joydip Kanjilal
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$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!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
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 from Microsoft is a new ADO.NET development framework that provides a level of abstraction for data access strategies and solves the impedance mismatch issues that exist between different data models This book explores Microsoft’s Entity Framework and explains how it can used to build enterprise level applications. It will also teach you how you can work with RESTful Services and Google’s Protocol Buffers with Entity Framework and WCF. You will explore how to use Entity Framework with ASP.NET Web API and also how to consume the data exposed by Entity Framework from client applications of varying types, i.e., ASP.NET MVC, WPF and Silverlight. You will familiarize yourself with the new features and improvements introduced in Entity Framework including enhanced POCO support, template-based code generation, tooling consolidation and connection resiliency. By the end of the book, you will be able to successfully extend the new functionalities of Entity framework into your project.
Publication date:
August 2015
Publisher
Packt
Pages
274
ISBN
9781783550012

 

Chapter 1. Introducing the ADO.NET Entity Framework

Welcome to our journey into mastering the popular data access technology from Microsoft named Entity Framework. At the time of writing, Entity Framework 7 hasn't been released—so we will use Entity Framework 6.x throughout this book but at the same time discuss what's new in Entity Framework 7.

Object Relational Mapping (ORM) technology has been widely in use for over a decade. ORMs are used to convert data between incompatible type systems. These are tools that encapsulate calls to the underlying database and enable you to query and manipulate data using an object-oriented paradigm.

The figure that follows illustrates the persistence layer that is responsible for reading and manipulating data to and from the database. Now, this persistence layer can be your ADO.NET library, a wrapper around the ADO.NET library, or an ORM:

We will explore more on ORMs later in this chapter. The ADO.NET Entity Framework (EF) is an extended and open source 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. In this book, we will examine Entity Framework 6 in order to leverage its existing and enhanced features to design and implement applications that are robust, high-performing, persistence, ignorant, and scalable. We will explore each of these features as we read through the chapters of this book.

This chapter will give you an introduction to Entity Framework and also provide 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 through Entity Framework 6 has just begun!

In this chapter, we will cover the following points:

  • An overview of Entity Framework

  • Entity Framework architectural components:

    • The Entity Data Model

    • LINQ to Entities

    • Entity Client

    • Entity SQL

    • The Object Services Layer

  • A comparative analysis of EF and other ORMs

  • New features and enhancements in Entity Framework 6:

    • Support for persistence ignorance

    • Support for T4 code generation

    • Support for lazy loading

    • Support for POCO change-tracking

    • Better n-tier support

    • Support for model-first and development

    • Support for built-in functions and UDF

    • Support for model-defined functions

    • Support for enums

    • Support for spatial data types

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

 

What you should know


As Entity Framework 7 has not been released and isn't mature yet, we will use Entity Framework 6.x in this book while discussing the features of Entity Framework 7 as we move ahead.

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

  • Programming using ADO.NET

  • C# 5.0

  • Using the Visual Studio 2013 IDE

  • Working with the .NET console and web applications

  • SQL Server 2012 or later

 

Looking back


Data-centric applications have two perspective layers. They are the data model and the object model. While the data model defines the way data is defined and stored, the object model defines how the same data will be represented to the user in the presentation layer or how it 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 a set of tables, views, functions, procedures, and relationships. You typically use T-SQL to query against the relational store, which returns result sets that contain columns and rows of data.

However, the data returned doesn't necessarily match 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 into business objects in the data access layer of the application. Similarly, you need to 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?

Here's exactly where an ORM fits in. The figure given next shows how objects in an application can be mapped to the relational store by using a mapping layer. This mapping layer is provided by the ORM. An ORM is a method of representing the relational tables as entities in the object world. ORMs came onto the market to provide you with a framework using which you can connect your applications to the underlying database without having to write much code. Most importantly, you can use ORMs to connect to any database, increase development productivity, ensure database independence, and database portability.

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.

Microsoft first released its ORM by the name of LINQ to SQL, which shipped with .NET Framework 3.5 and Visual Studio 2008. However, LINQ to SQL was restricted to working with SQL Server databases only. Entity Framework is an attempt by Microsoft to provide you with an extended ORM built on top of the ADO.NET provider model and enable you to connect to and work with any database.

 

What is the ADO.NET Entity Framework?


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 is illustrated using the self-explanatory diagram that follows:

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, and so on, 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. Also, Entity Framework provides support to cache data automatically by default.

Is Entity Framework 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.

Note

Factory classes are based on the factory design pattern and are used to create instances of classes without exposing the instantiation logic to the client.

On the contrary, using 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 among themselves.

The major difference between Entity Framework and ORM tools is the EDM and the former's ability to query data using strongly typed LINQ. You can even use Entity SQL, a T-SQL-like query language to query the EDM, to execute dynamic queries. In addition to what a typical ORM framework provides, the 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. Please refer to the Appendix section for links to resources on this topic.

Entity Framework even enables you to 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.

 

A comparative analysis of Entity Framework and other ORM tools


Data access strategies have changed over the years. From Remote Data Objects (RDO), Data Access Objects (DAO), to ADO.NET, the industry has seen a marked improvement in the way data is accessed these days.

ORM tools enable you to access data from persistent storage devices without having to bother about how the underlying data is actually stored. NHibernate is a lightweight ORM tool for .NET. It has a statically compiled counterpart called Fluent NHibernate. Fluent NHibernate provides you with an XML-less, compile safe, automated NHibernate mapper with LINQ support. Domain modeling is an area where Entity Framework scores over NHibernate.

Consider the following entity class:

public class User
    {
        public virtual Int32 UserID { get; set; }        
        public virtual String UserName { get; set; }
        public virtual String CreatedBy { get; set; }
        public virtual DateTime CreatedDate { get; set; }        
        public virtual String ModifiedBy { get; set; }
        public virtual DateTime ModifiedDate { get; set; }
    }

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The following class illustrates how you can create a mapping for the preceding class by extending the generic ClassMap<T> class:

public class UserMap : ClassMap<User>
    {
        public UserMap()
        {
            Table("Users");
            Id(x => x.UserID).GeneratedBy.Identity();
            Map(x => x.UserName);
            Map(x => x.CreatedBy);
            Map(x => x.CreatedDate);          
            Map(x => x.ModifiedBy);
            Map(x => x.ModifiedDate);
        }
    }

The following code example illustrates how you can create a data gateway for the User entity class:

using FluentNHibernate;
using NHibernate;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Automapping;
using NHibernate.Cfg;
using NHibernate;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Automapping;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System.Reflection;
namespace Packt
{
    public static class DataManager
    {
        private static ISessionFactory sessionFactory = null;
        private static readonly string businessObjectsNamespace = 
        "Packt.Entity.Mappings";
        private static readonly string connectionString = @"Data 
        Source=JOYDIP-PC\SQLServer2014;
        Initial Catalog=Security;Integrated Security=True";
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
      //Code to create a new session factory instance and load the 
      business entities
                }   
             return sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}

Note that you can make a call to DataManager.OpenSession() to open the database connectivity session.

Entity Framework 6 is a mature ORM and comes up with many powerful features. When you use Entity Framework, you can concentrate more on writing application logic rather than writing the database connectivity code. This reduces development time and effort greatly.

Language Integrated Query (LINQ) is a query translation pipeline that you can use to integrate your queries into the object model. LINQ provides you with a framework that you can use to access relational data in a strongly typed way. LINQ provides a great way to query in-memory objects.

Here are the various forms that LINQ comes up with:

  • LINQ to objects: This is used to query in-memory objects or a collection of in-memory objects

  • LINQ to XML: This is used to query data retrieved from XML data sources

  • LINQ to SQL: This is used to query data retrieved from SQL Server database

  • LINQ to DataSet: This is used to query data from a DataSet or a DataTable

  • LINQ to Entities: This is used to query data exposed by the EDM

The LINQ library contains two primary interfaces that all generic collection classes implement. These are the IEnumerable<T> interface and the IQueryable<T> interface. While the former exposes an enumerator to iterate over a collection of a given type T, the latter provides a functionality to query a data source that will implement this interface. Also, IQueryable allows you to filter data on the server side.

The following diagram illustrates how these interfaces are related:

Important interfaces of the LINQ library

LINQ to SQL and .dbml files

LINQ to SQL allows you create an object model that maps to the tables in the relational database. The object relational mapping implementation of LINQ to SQL handles the execution strategy of the SQL queries. A database markup language file, also known as .dbml file, is generated by the Visual Studio IDE when you drag and drop database tables from the solution explorer onto the LINQ to SQL design surface. When each table is dragged on the design surface, a class is created for each table. These classes are known as entity classes and they are partial classes.

Both LINQ to SQL and ORM share certain common behaviors in terms of designing, mapping entities with relational database, and querying entities.

Developing non-LINQ to SQL data-centric applications may consume a lot time and effort in trying to build custom components that will interact with the data source. LINQ to SQL maps tables to classes, which helps architects to design a better n-tier architecture, thus improving productivity.

The properties in the entity classes are mapped to the columns in the table with an appropriate data type mapping scheme. Hence, a compile time check is performed that reduces runtime errors.

 

Entity Framework architectural components


Entity Framework comprises the following components:

  • The Entity Data Model

  • LINQ to Entities

  • Entity Client

  • Entity SQL

  • The Object Services Layer

Note that the Conceptual Model Layer, Mapping Layer, and Logical Model Layer are all parts of the EDM. The following image illustrates the layers of the ADO.NET Entity Framework and how they are related to each other:

ADO.NET Entity Framework: the architectural components

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

The Entity Data Model

The Entity Data Model (EDM), an extended entity relationship model, is the core of Entity Framework. You can generate an EDM using the EDMGen.exe command-line tool or using the ADO.NET EDM Designer—a new Visual Studio template. We will discuss how an EDM can be generated from a relational schema in the next chapter.

For additional information, please refer to http://msdn.microsoft.com/en-us/library/bb896270(v=vs.110).aspx.

The following image illustrates where exactly the EDM fits in:

The Entity Data Model

The EDM abstracts the logical or the relational schema and exposes the conceptual schema of the data using a three-layered approach. It comprises the following layers:

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

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

  • The Storage Layer or the Logical Layer or the Store Space Definition Language Layer (S-Space)

The following image illustrates the layers of the EDM:

The Entity Data Model layers

Let's explain each of these layers in detail:

  • 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 comprises 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 Mapping Storage Layer or the MSL.

  • The Logical or the Storage Layer (also called the S-Space) represents the schema of the underlying database. This comprises tables, stored procedures, views, and functions. It is modeled using SSDL and queried using the database providers. A database provider is an API to connect to and perform CRUD operations against a database. As an example, if the database in use is SQL Server, the ADO.NET data provider for SQL Server will be used. Hence, we use SQLConnection, SQLCommand, SQLDataReader, and SQLDataAdapter using T-SQL or PL-SQL if our data store is a SQL database.

Here is what a typical EDM looks like:

An ADO.NET Entity Data Model at a glance

How is the EDM represented?

The EDM uses the following three types of XML files to represent the C-Space, C-S Space, and the S-Space respectively:

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

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

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

    Note

    If you use the ADO.NET EDM Designer tool to generate your EDM, 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 preceding layers.

Note

You can also create abstract and complex types in your EDM. 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 EDM until Chapter 3, Entities, Relationships, and the Entity Data Model.

The Object Model (O-Space)

When working with Entity Framework, you will have an Object Model on top of all the EDM 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 and its relationship with other layers

The Object Model layer contains .NET objects and a 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

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, and so on). It is an extension of the C# language (it's actually a series of extension methods) and provides a simplified framework to access 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. You will learn more about LINQ and LINQ to Entities in Chapter 6, Working with LINQ to Entities.

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

AdventureWorksEntities ctx = new AdventureWorksEntities();
            var query = from e in ctx.Employees
               select e;
            foreach (var employee in query)
                Console.WriteLine (employee.EmployeeID);

Note

LINQ to Entities rests on top of Entity Framework's Object Services Layer and 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

The Entity Framework allows you to write programs against the EDM and also add a level of abstraction on top of the relational model. This isolation of the logical view of data from the Object Model is accomplished by expressing queries in terms of abstractions using an enhanced query language called Entity SQL.

EntityClient, 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 the entity connection, execute commands through entity commands, and retrieve the result sets as entity data readers. The MSDN states:

"The EntityClient provider is a data provider used by Entity Framework applications to access data described in a conceptual model."

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 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 your EDM? 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 the ADO.NET data providers.

Here is an example that shows how you can use Entity SQL to insert data into 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)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

Note

To query data from the EDM, 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 therefore require more complex joins.

When you implement your Object Model using object-oriented programming languages, you expose the object's relationships to 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 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

This is how you would use Entity SQL to achieve the same result:

Select FirstName, LastName, DepartmentName, Basic from Employee

In the previous example, EmployeeData is an entity that has been derived from the Employee, Department, and Salary entities.

The Object Services Layer

As well as 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, and with less code.

Note

You can query data from the EDM by either using Object Services or EntityClient. 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.

Note that the Object Services Layer internally uses an ObjectQuery object for query processing. To use object services, you should include the System.Data.Objects and System.Data.Objects.DataClasses namespaces.

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

using (ObjectContext ctx = new ObjectContext("Name= PayrollEntities"))
            {
                ObjectQuery<Employee> data = ctx.CreateQuery<Employee>("PayrollEntities.Employees");

                foreach (Employee emp in data)
                {
                    Console.WriteLine(emp.EmployeeID);
                }
            }

In addition to enabling you to perform create, read, update, and delete (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

You will learn more about Object Services later in the book. The Object Services Layer leverages an Object Query object internally to process the data. Note that the Object Services Layer supports querying data using both Entity SQL and LINQ to Entities.

Features and benefits at a glance

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

  • It provides support for an increased level of abstraction on top of the underlying data store

  • It provides support for extensibility and seamless querying of data using Entity SQL and LINQ

  • It is a flexible schema that can be used to store the mapping information

  • There is a reduction in the amount of Kilo Lines of Code (KLOC) needed to write data access code in your applications

  • It contains a powerful Object Services Layer

  • It provides support for a full text-based query language

  • It provides support for persistence ignorance

  • IT provides support for lazy loading

    Note

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

 

System requirements


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

Note that Entity Framework 6.0 already ships with Visual Studio 2013, so there is no need to download it if you use this version of Visual Studio.

Now let's take a quick look at each of these new features. We will explore each of these features in detail as we move through the chapters.

Support for persistence ignorance

Support for persistence ignorance was introduced in Entity Framework 4.0. Persistence ignorance, as the literal meaning implies, is a concept that enables you to build your applications in a way that can just ignore the underlying data store in use. In essence, you can build applications that can have different persistent technology in future.

You can now create your own Plain Old CLR Objects (commonly known as POCO) that are decoupled from any specific persistence technology. To provide support for POCO, all you need to do is just turn off code generation in the model in your Visual Studio 2013 IDE.

You can simply clear the values of the Custom Tool property of your EDM and save it again. Once you have done this, you have to create your own custom object context by deriving your custom object context class from the ObjectContext class. Then you can define the data members and properties in your custom object context class as per your needs.

Support for T4 code generation

T4 is a code generation technology that was introduced in Visual Studio 2008. T4 templates not only give you advantage to customize the generated code, they also generate less code, concealing a lot of redundant functions that were present in the old generated code. Entity Framework 6 provides support for T4 code-generation templates. You can also customize these templates as needed.

Support for lazy loading

Lazy loading is a concept that enables an entity to be loaded late— it's loaded on demand actually. Entity Framework 6 provides better support for lazy loading. To enable deferred loading (it is turned off by default), you should make use of the DeferredLoadingEnabled property. Please check out this URL for more information on lazy loading http://msdn.microsoft.com/en-us/library/vstudio/dd456846(v=vs.100).aspx.

Note

Deferred loading works with both code-generated entities as well as your Plain Old CLR Objects—commonly known as POCO entities.

Support for POCO change tracking

Entity Framework 6 enables you to easily track changes to POCOs. Note that Entity Framework 6.0 provides support for the deferred or lazy loading of entities with POCO classes through the usage of proxy types. Here is an example:

var result = (from emp in PayrollDataContext.Employee
.Include("Department") where emp.DepartmentID == 12 select emp).Single();

Please check out this URL to find out more about lazy loading:

http://msdn.microsoft.com/en-us/library/vstudio/dd456846(v=vs.100).aspx

We will explore more about POCO classes and lazy loading later in this book.

Better n-tier support with self-tracking entities

Entity Framework 6 provides better n-tier support and support for self-tracking entities. Self-tracking entities are those that enable each entity to track any changes to themselves so that you can pass it across process boundaries and persist the entire object graph. Entity Framework 6 includes T4 templates to generate entities that have the ability to track their own changes on the client side.

Support for code-first, model-first, and database-first approaches

Entity Framework 6 now enables you to generate your Data Model from the conceptual model. You can now create your entities and then use Visual Studio 2013 to generate the database based on a predefined conceptual model.

In the code-first approach, the domain model is first defined using POCO classes and then the database is created from these classes. This approach is popular and provides much more control over your code—you just need to define the database mappings and leave the creation of the database entirely to Entity Framework. Note that as your code drives the database, manual changes to the database are not recommended in this approach.

The figure given next illustrates the three approaches and why and when each should be used:

In the model-first approach, you create your entities, relationships, and the inheritance hierarchies directly on the design surface of the EDM Designer in Visual Studio and then generate the database from the model designed. If you need additional features, you can use partial classes. In essence, in this approach, the model drives and defines the database. This is also known as the model-driven approach. This approach is good for small projects, but with complex databases and large projects this is not a preferred approach as you don't have much control over the database. Also, making manual changes to the database schema is also not recommended.

In the database-first approach, you would create your database first and then generate your model using the ADO.NET EDM Designer from this database.

Support for built-in functions and UDF support

Entity Framework 6 provides support for you to use SQL Server functions directly in your queries. Here is an example:

from emp in PayrollDataContext.Employee
where new[] {"january","february","march"}.Contains(SqlFunctions.DateName("month", emp.JoiningDate))
orderby emp.EmployeeID
select new 
{
 emp.EmployeeID,emp.JoiningDate
};

Support for model-defined functions

Entity Framework 6 now provides support for model-defined functions that can be defined in the CSDL using eSQL. Note that model-defined functions support LINQ to Entities and can also be called Object methods. Here is an example:

<Function Name="GetEmployeeAge" ReturnType="Edm.Int32">
    <Parameter Name="Employee" Type="Self.Employee" />
      <DefiningExpression>
        Edm.DiffYears(Employee.BirthDate, Edm.CurrentDateTime())
      </DefiningExpression>
</Function>.

In this section, we just gave you an introduction to the new features in Entity Framework 6—we will cover details of each of these features in the forthcoming chapters of this book.

Enum support

Enum support is a much-awaited feature that enables you to have enum properties in your domain classes. In Entity Framework 6, you have enum support both in the EF Designer as well as using a code-first approach. To create an enum in Entity Framework 6, all you need is to create a scalar property of type Int32 in the EDM, select it, right-click on it, and then select Convert to Enum. The following image illustrates this:

In the preceding image, IsRetired has been introduced as a scalar property of type Int32. You can see that the Convert to Enum option is enabled.

Spatial data types support

Spatial data types are actually geography and geometry-related classes that allow us to work directly with such data inside the SQL Server. Spatial data can be of two types—the geometry data type that provides support for planar or Euclidean (flat-earth) data, and geography data type that can store ellipsoidal (round-earth) data such as GPS latitude and longitude coordinates. Entity Framework 6 now provides support for spatial data types using the DbGeography and DbGeometry types. You can include spatial data in your models both using the EF Designer, as well as using code-first. You can find out more about spatial data types from this link: http://technet.microsoft.com/en-us/library/bb964711.aspx.

Note

Some of the new features in Entity Framework 6 such as enum support and spatial data types will work with .NET Framework 4.5 and above.

Other enhancements

In Entity Framework 6, DbContext is the default generated context. It is not new though. It is a wrapper around ObjectContext generated using T4 templates. Here is an example:

      public AdventureWorksEntities()
            : base("name=AdventureWorksEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder 
        modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Department> Departments { get; set; }
        public virtual DbSet<Employee> Employees { get; set; }
        public virtual DbSet<EmployeeDepartmentHistory> 
        EmployeeDepartmentHistories { get; set; }
        public virtual DbSet<EmployeePayHistory> 
        EmployeePayHistories { get; set; }
        public virtual DbSet<JobCandidate> JobCandidates { get; 
        set; }
        public virtual DbSet<Shift> Shifts { get; set; }
    }

The other enhancements in Entity Framework are shown as follows:

  • Task-based asynchronous operation: This allows Entity Framework to take advantage of .NET 4.5 asynchronous support with asynchronous queries, updates, and so on. Entity Framework 6 now provides support for a simplified approach to asynchronous programming. Entity Framework 6 can now be used to run async queries and also save data asynchronously.

  • Enhanced support for stored procedures and functions in code first : This feature allows you to map stored procedures and database functions by using the code-first APIs.

  • Support for custom code first conventions: This is a feature that allows you to write and register custom code conventions with code first.

    Note

    Note that the third-party providers for Entity Framework 5 are not compatible with Entity Framework 6. This implies that if you are using the SQL Server or SQL Server Compact editions, you should update the database providers.

 

Performance improvements in Entity Framework 6


In Entity Framework 6, query performance has been improved a lot. One important performance improvement is in precompiled queries. A compiled query is one that is stored as a parsed tree in memory so that it needn't be regenerated with every subsequent call. You can create compiled queries in two ways: creating an ObjectQuery class with EntitySQL and also using the CompiledQuery.Compile function. Compiling expression trees into SQL every time is an overhead particularly for queries that are complex. This is exactly why compiled queries were introduced.

The earlier versions of Entity Framework contained the CompiledQuery class that you could use to precompile the query and then execute the query as and when needed. So, in essence, when using precompiled queries, the SQL to be executed is figured out only once (during precompilation) and this is then reused each time the compiled query is executed.

Note

Note that if you are using CompiledQuery, you should make sure that you are using the query more than once. This is because it is more costly than querying data the first time.

Now, what were the downsides? You cannot use CompiledQuery using the DbContext API as it only works with ObjectContext. Note that the support for compiled query was revoked from the DbContext API due to some technical limitations. If you use a code-first strategy, you will most likely be opting for the DbContext API. Thankfully, Entity Framework 6 solved this problem, so you no longer need to make this choice.

With Entity Framework 6, you have a feature called auto-compiled queries—this works very different from the way CompiledQuery works. You no longer need to write code to compile each query and then invoke as needed. How does it work then? Entity Framework stores the generated SQL in the cache using a background thread and then as and when needed (based on the calls made), it searches the compiled queries in the cache. This is illustrated in the following image:

Auto-compiled query in Entity Framework

You can also turn off query caching if you need to. The new ObjectContext.ContextOptions property allows you to control the default behavior of the query compilation. This property is set to true by default, but you can set it to false to turn off the auto-compilation of your queries. Here is an example:

dataContext.ContextOptions.DefaultQueryPlanCachingSetting = false;

If you are using DbContext, you should cast to IObjectContextAdapter, as shown in the following code:

((IObjectContextAdapter)dataContext).ObjectContext.ContextOptions.DefaultQueryPlanCachingSetting = false;
 

New features in Entity Framework 7


Entity Framework 7, a major redesign of the ORM, is the latest version of Entity Framework with the vision of "New Platforms, New Data Stores."

Some of the striking features of this release include support for the following:

  • Non-relational data stores and in-memory data: You can now use Entity Framework with NoSQL databases as well.

    Entity Framework 7 now provides support for the following data providers:

    • SQL Server

    • SQLite

    • Azure Table Storage

    • Redis

    • In memory (for unit testing)

  • Windows Phone and Windows Store applications and the Linux and Macintosh systems: Entity Framework 7 now provides support for Windows Phone, Windows Store, and ASP.NET 5 and desktop applications.

  • Unit testing: Entity Framework 7 now provides support to unit test your applications against in-memory or memory-resident databases.

 

Summary


Entity Framework mainly addressees how easily you can persist and query your data with many added services. You can use 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 explored Entity Framework and the architectural components of Entity Framework, and provided a comparative analysis between Entity Framework and other ORM tools. In the next chapter, you will learn how to get started with Entity Framework.

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
Latest Reviews (1 reviews total)
On this occassion, this book wasn't really what I was looking for. We're trying to switch to Entity Framework in an open source VB.NET project and we need straigh forward examples to follow. The book seems to give the authors experience and perspective with other languages and use cases, but isn't really helpful for our situation.
Entity Framework Tutorial (Update) - Second Edition
Unlock this book and the full library FREE for 7 days
Start now