Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Entity Framework Tutorial (Update)

You're reading from   Entity Framework Tutorial (Update) A comprehensive guide to the Entity Framework with insight into its latest features and optimizations for responsive data access in your projects

Arrow left icon
Product type Paperback
Published in Aug 2015
Publisher
ISBN-13 9781783550012
Length 274 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Joydip Kanjilal Joydip Kanjilal
Author Profile Icon Joydip Kanjilal
Joydip Kanjilal
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Introducing the ADO.NET Entity Framework FREE CHAPTER 2. Getting Started 3. Entities, Relationships, and the Entity Data Model 4. Working with Stored Procedures in the Entity Data Model 5. Working with Entity Client and Entity SQL 6. Working with LINQ to Entities 7. Working with the Object Services Layer 8. Working with WCF Data Services A. Advanced Concepts Index

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:

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

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:

Enum support

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.

You have been reading a chapter from
Entity Framework Tutorial (Update) - Second Edition
Published in: Aug 2015
Publisher:
ISBN-13: 9781783550012
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image