Book Image

Entity Framework Tutorial (Update) - Second Edition

By : Joydip Kanjilal
Book Image

Entity Framework Tutorial (Update) - Second Edition

By: Joydip Kanjilal

Overview of 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.
Table of Contents (16 chapters)
Entity Framework Tutorial Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
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:

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.