A Look At The New Features In The ADO.NET Entity Framework 4.0

Introduction

The ADO.NET Entity Framework 4.0 ships with Microsoft Visual Studio 2010 and offers a lot of new and enhanced features. This article discusses these features and enhancements with code examples wherever applicable.

What is the ADO.NET Entity Framework?

The ADO.NET Entity Framework is an extended Object Relational Mapping (ORM) Microsoft that can be used to abstract the object model of an application from its relational or logical model.

The Entity Framework is comprised of three layers. These are:

  • The Conceptual Layer - Represented using CSDL (Conceptual Data Language)
  • The Storage Layer - Represented using SSDL (Store-specific Data Language)
  • The Mapping Layer - Represented MSL (Mapping Schema Language)

The major components of the ADO.NET Entity Framework include:

  1. The Entity Data Model - An entity relationship model
  2. LINQ to Entities - Used to query the Entity Data Model using strongly typed LINQ queries.
  3. The Entity Client - a provider that works on top of the ADO.NET provider and can be used to query the Entity Data Model using Entity SQL or eSQL, having syntax similar to what we use in T-SQL.
  4. The Object Services Layer - can be used to query data using LINQ to Entities

Why The ADO.NET Entity Framework?

The ADO.NET Entity Framework was designed by Microsoft to objectify your application's data and in doing so, isolate the logical or relational model of your application from the object model. Support for entity inheritance, entity composition and change tracking are some of the key features of the entity Framework that make it a better ORM. The MSDN states, "A primary goal of the ADO.NET Entity Framework is to raise the level of abstraction available for data programming, thus simplifying the development of data aware applications and enabling developers to write less code. The Entity Framework is the evolution of ADO.NET that allows developers to program in terms of the standard ADO.NET abstraction or in terms of persistent objects (ORM) and is built upon the standard ADO.NET Provider model which allows access to third party databases." Also, unlike LINQ to SQL, you can use Entity Framework to store data in any data store provided you have the right ADO.NET provider with you.

New Features and Enhancements in the ADO.NET Entity Framework 4.0

ADO.NET Entity Framework 4.0 was earlier named, ADO.NET Entity Framework 2.0". It has been renamed to ADO.NET Entity Framework 4.0 to maintain parity with .NET Framework 4.0. ADO.NET Entity Framework 4.0 now ships With Visual Studio 2010. There have been a lot of improvements to the Entity Framework 4.0 compared to its earlier counterparts. Julia Lerman states: "The changes in EF4 include numerous major improvements to the designer, the addition of model-first design, a new way to customize classes that are generated from the model, the ability to create POCO classes (Plain Old CLR Objects) that can be used in EF without having to be strongly bound to the EF APIs, and additions that will make using entities across processes (e.g. Web services) much easier for developers."

Reference: http://www.code-magazine.com/Article.aspx?quickid=0909081

The new features and enhancements in ADO.NET Entity Framework 4.0 include:

  1. Persistence Ignorance
  2. Lazy Loading
  3. Better N-Tier Support
  4. Model-First and Code Only Development
  5. Built-In Functions, UDFs and Model Defined Functions

The sections that follow discuss each of these features in detail.

Support for Persistence Ignorance

Persistence ignorance is one of the most important features that have been introduced in Entity Framework 4.0 - a feature that was missing in the earlier versions of this framework. Persistence ignorance is a concept that states that when an object is persisted in a persistent medium, the underlying details of the object are hidden or ignored. Here the term ignorance implies that the underlying details of how an object can be persisted are "encapsulated". In essence, persistence ignorance is a concept that enables you to design your Entity Data Model where the conceptual model is independent of the physical model.

Persistence ignorance enables you to design and implement applications that are independent of the persistent technology being used. You can now even create your own Plain Old CLR Objects (commonly known as POCO). Such objects are not dependent on any specific persistent technology in particular.

Support for POCO is now provided by your Microsoft Visual Studio 2010 IDE - you just need to turn off code generation in the model and clear the values of the Custom Tool property of your model and save it again. To create your own custom object context, you can simply derive from the ObjectContext class and define the data members and properties you need. The Entity Framework 4.0 even allows you to track changes made to the POCO objects seamlessly.

Here is an example of a simple POCO class:

public class Student
{   
    public int StudentID { get; set; }   
    public string FirstName { get; set; }   
    public string LastName { get; set; }   
    public string Address { get; set; }   
}  

You can derive from the ObjectContext base class to create your own custom data context as shown in the code snippet below:
public class CodeGuruObjectContext : ObjectContext   
{   
    public CodeGuruObjectContext(string connectionString)   
        : base(connectionString, "CodeGuruObjectContext")   
    {   
    }   
  
    private IObjectSet<Student> _studentSet;   
  
    public IObjectSet<Student> StudentSet    
    {   
        get    
        {   
            if (_studentSet == null)   
            {   
                _studentSet = CreateObjectSet<Student>();   
            }   
            return _studentSet;   
        }   
    }   
}  

Now, you can use the custom object context you have just created to retrieve data as shown in the code example that follows:
public static void Main(string[] args)   
{   
 using (var dataContext = new CodeGuruObjectContext("name=CodeGuruObjectContext"))   
 {   
    try  
    {   
        var student = dataContext.StudentSet.First();   
        Console.WriteLine(student.FirstName + " "+student.LastName);   
    }   
    catch (Exception ex)   
    {   
        Console.Write(ex.ToString());   
    }   
 }   
}

Model First Development

In the earlier versions of the Entity Framework you have had to design your relation model first and then use it to design your Entity Data Model. The Entity Framework 4.0 provides support for Model First development, a design strategy where you can drive your physical or logical model from the conceptual model. You can now use the Visual Studio 2010 IDE to create your entities and then generate your relational or logical model from the conceptual model.

Lazy Loading

The Entity Framework 4.0 provides enhanced support for Lazy loading. Lazy loading is a concept that allows your entities to be loaded late in the memory. You can use the ContextOptions.LazyLoadingEnabled property of the DataContext to implement lazy loading. The following code snippet illustrates this:

using (var dataContext = new CodeGuruEntities())
{
   dataContext.ContextOptions.LazyLoadingEnabled = true;
   //usual code
}

Better N-Tier Support with Self-Tracking Entities

The Entity Framework 4.0 provides enhanced support for designing and implementing N-tier applications and self tracking entities. Self tracking entities are those entities that have the ability to track changes made to it. You can now use T4 templates available as part of Entity Framework 4.0 to generate entities that can track changes to it. Also, the T4 templates provide you much better control on the generated entity classes. Self tracking entities are a great help in designing and implementing N-tier applications where the entities would reside at the client side and the changes to the entities need to be tracked and persisted in a persistent storage medium.

Built-In Functions, UDFs and Model Defined Functions

The Entity Framework 4.0 now provides support for using built-in SQL Server functions and also User Defined Functions (UDFs). You can now use your SQL Server functions directly when writing your queries against the Entity Data Model. The following code snippet illustrates this:

from s in CodeGuruDataContext.Student
where new[] {"january","february","march"}.Contains(SqlFunctions.DateName
("month", s.BirthDate))
orderby s.FirstName
select new 
{
 s.StudentID,s.FirstName,s.LastName
};

Model Defined Functions are those that can be defined in your Entity Data Model. The Entity Framework enables you to define functions CSDL using Entity SQL (eSQL). The following code snippet illustrates how you can do this:

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

Summary

The Entity Framework 4.0 promises to fill the gaps in its earlier releases and is all set to become one of the most popular ORMs of its kind with many powerful features. This article presented the new features and enhancements in ADO.NET Entity Framework 4.0. You can know more on ADO.NET Entity Framework 4.0 from my book titled, "Entity Framework Tutorial". The next edition of this book (updated to cover Entity Framework 4.0), would be released in a few months from now. Here is the link to the book at Amazon: http://www.amazon.com/Entity-Framework-Tutorial-Joydip-Kanjilal/dp/1847195229/



About the Author

Joydip Kanjilal

Microsoft Most Valuable Professional, Author and Speaker. Featured in "MSDN Featured Developer of the Fortnight (India)" a number of times. Winner of Community Credit Awards at www.community-credit.com several times. Authored numerous books and articles in Microsoft .NET and its related technologies. Authored the following books:-- 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)

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • This ESG study by Mark Peters evaluated a common industry-standard disk VTl deduplication system (with 15:1 reduction ratio) versus a tape library with LTO-5, drives with full nightly backups, over a five-year period.  The scenarios included replicated systems and offsite tape vaults.  In all circumstances, the TCO for VTL with deduplication ranged from about 2 to 4 times more expensive than the LTO-5 tape library TCO. The paper shares recent ESG research and lots more. 

  • Live Event Date: September 16, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you starting an on-premise-to-cloud data migration project? Have you thought about how much space you might need for your online platform or how to handle data that might be related to users who no longer exist? If these questions or any other concerns have been plaguing you about your migration project, check out this eSeminar. Join our speakers Betsy Bilhorn, VP, Product Management at Scribe, Mike Virnig, PowerSucess Manager and Michele …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds