ADO.NET Entity Framework 4: New and Notable Features

The ADO.NET Entity Framework is an extended object relational mapping (ORM) tool from Microsoft that has become increasingly popular over the past few years and is widely used these days. Microsoft designed the ADO.NET Entity Framework to objectify an application’s data and simplify the development of data-aware applications.

In the first article in this series on the ADO.NET Entity Framework, I discussed the basics and how to program against the Entity Data Model. This concluding article, I will discuss the new features in Entity Framework 4.

Entity Framework 4.0 Prerequisites

To work with Entity Framework and the code examples illustrated in this article, you should have the following installed in your system:

  • Visual Studio 2008 with SP1
  • Entity Framework Version 4

Alternatively, you can simply have Visual Studio 2010 installed — it comes with Entity Framework 4 by default.

Code First Development with Entity Framework 4

Entity Framework 4 supports “code first development,” enabling you to use the Entity Framework designer tool to design your object model and then use it to drive your relational or logical model.

Programming the Entity Data Model

You have a few choices for writing queries and executing them against the Entity Data Model, namely Object Services, Entity Client and LINQ.

While Entity Client is the data provider to connect to the Entity Data Model and perform CRUD operations, Entity SQL is a data store-independent derivative of T-SQL. The following code snippet shows how you can use Object Services to query your data:

using (NorthwindEntities dataContext = new NorthwindEntities())    {        ObjectQuery products =            dataContext.CreateQuery(                "SELECT VALUE p FROM Products AS p");        foreach (Products p in products)        {            Console.WriteLine(p.ProductName);        }    }

The same query can be re-written using LINQ as shown in the code snippet below:

using (NorthwindEntities dataContext = new NorthwindEntities())    {        var result = from p in dataContext.Products select p;        foreach (Products product in result)        {            Console.WriteLine(product.ProductName);        }    }

The Entity Client supports only Entity SQL as the query language. This is in contrast to Object Services, which allows you to use even LINQ to write your queries and execute them against the Entity Data Model. The following code snippet illustrates how you can use Entity Client:

using (EntityConnection conn = new     EntityConnection("name=TestEntities")){    conn.Open();    EntityCommand cmd = conn.CreateCommand();    cmd.CommandText = @"SELECT VALUE e FROM TestEntities.Managers AS e";    using (DbDataReader reader =         cmd.ExecuteReader(            CommandBehavior.SequentialAccess))    {        while (reader.Read())        {            Console.WriteLine(                "Manager Name: {0}",                 reader["ManagerName"].ToString());        }    }}

Support for Persistence Ignorance

Support for persistence ignorance is one of the most striking features in Entity Framework 4. What is it, you ask? Persistence ignorance is a concept introduced in Entity Framework 4 that encapsulates the underlying details of an object while it is being persisted in a persistent medium. So, you can design your conceptual model without having to be bothered about the intricacies of the underlying relational model.

You can also design your own Plain Old CLR Objects (commonly known as POCOs). POCOs are simple objects that are not dependent on any specific persistent technology. Here is an example of a POCO class:

public class Product    {        public Int32 ProductID { get; set; }        public String ProductName { get; set; }        public Int32 SupplierID { get; set; }        public Int32 UnitQuantity { get; set; }        public decimal UnitPrice { get; set; }        public Int32 UnitsInStock { get; set; }        public Int32 UnitsOnOrder { get; set; }        public Int32 ReorderLevel { get; set; }        public bool Discontinued { get; set; }    }

Another great feature in Entity Framework 4 is the ability to design the Object Model first (using the Visual Studio 2010 Entity Data Model Designer, if you use VS2010) and then use it to design the Relational Model. This ability is commonly known as Model First Development.

Handling Concurrency Conflicts

The Entity Framework supports optimistic concurrency by default. This implies that by default it doesn’t check for concurrency while updating data. You can, however, change this behavior. To do so, you need to use the property called ConcurrencyMode in your Entity Data Model. Here’s an example:

When you use this attribute on your Entity in the Entity Data Model and a conflict occurs, an OptimisticConcurrencyException is thrown. To handle this exception, you can use the Refresh() method of the ObjectContext class. The Refresh() method has the following signature:

public void Refresh(RefreshMode refreshMode,Object entity)

The RefreshMode enumeration can accept one of the following two values:

  • ClientWins
  • StoreWins

The following code snippet illustrates how you can handle this:

try{    //Some code to save data    dataContext.SaveChanges();    Console.WriteLine("No conflicts, data saved successfully.";}catch (OptimisticConcurrencyException){    dataContext.Refresh(RefreshMode.ClientWins, orders);    dataContext.SaveChanges();    Console.WriteLine("OptimisticConcurrencyException has been handled and the changes saved successfully.");}

To use StoreWins, you can simply pass RefreshMode.StoreWins as a parameter to the Refresh() method of the data context as shown below:

try{    //Some code to save data    dataContext.SaveChanges();    Console.WriteLine("No conflicts, data saved successfully.";}catch (OptimisticConcurrencyException){    dataContext.Refresh(RefreshMode.StoreWins, orders);    dataContext.SaveChanges();    Console.WriteLine("OptimisticConcurrencyException has been handled and the changes saved successfully.");}

One of the best strategies to handle concurrency conflicts in Entity Framework is to have an extra column of type TimeStamp in your database table and then change the ConcurrencyMode of this column to Fixed in the Entity Data Model.

Suggested Readings

Here are a few links to further study on this topic:

Summary

ADO.NET Entity Framework 4.0 is a more mature ORM tool than its predecessors. In this two-part series on Entity Framework, I explored the basics, explained how to program against the Entity Data Model and explored some of its other notable features. You can learn more about ADO.NET Entity Framework 4.0 from my book, “Entity Framework Tutorial“.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: