Skip navigation

Renovations to .NET 4.0's Entity Framework

Entity Framework 4 offers a more intelligent, accessible framework

The ADO.NET Entity Framework (EF) was released last summer as part of Visual Studio (VS) 2008 SP1. This was the first round of Microsoft's long-term vision for the Entity Framework. VS 2010 brings us the next evolution of the Entity Framework and includes many major enhancements that are a result of valuable feedback from the community.

While there are myriad improvements throughout the Entity Framework, this article will focus on 11 of the most significant new features and changes in this version. Although this is the second iteration of EF, it is being referred to as Entity Framework 4 (EF4), to align with .NET 4.0, the new version of the .NET Framework. Two of the features covered in this article will be included in a separate installation referred to as the Entity Framework Feature Community Technology Preview (CTP). Eventually these will be rolled into Visual Studio and .NET, but not for the VS 2010 release to manufacturing (RTM). This article was written using VS 2010 Beta 1. I've noted known changes for Beta 2 and RTM.

1. Better Entity Naming by the EDM Wizard
One of the biggest problems with the VS 2008 Entity Data Model (EDM) designer is that the wizard does not automatically apply singular and plural names to entities when they're being generated from the database. An entity is a single item, therefore it is logical for its name to be singular. An EntitySet is a wrapper for a set of entities, therefore its name should be plural. However, the wizard merely duplicates the name of the tables from which the model is derived. As a result, developers spend a lot of time manually renaming entities, their EntitySets, and navigation properties in new models. This has been very frustrating, especially when there are a large number of entities in the model.

The EF4 wizard can now apply the appropriate names throughout the model. Figure 1 shows an example of a SalesOrderHeader entity. The wizard automatically applied the correct singular and plural forms to this entity. The navigation properties now relate to the multiplicity of their related entities (e.g., Address points to a single Address while SalesOrderDetails points to a collection of detail entities).

Not only does the wizard determine whether singular or plural is correct, but it also is capable of properly fixing up every English table name I've tried so far. For example, it correctly gives me People as the plural of Person and Breweries as the plural for Brewery. If the table name starts out as a plural name, the wizard ensures that the entity name is singular.

2. Model-First Design
Entity Framework version 1 (EF1) targets developers who want to build a model from an existing database. EF4 now allows developers to use the EDM Designer to create a model, then generate database schema from that model. The Designer has a new context menu option, Generate Database Script from Model. This feature will build a database script that you can then run in your database. The script doesn't create the actual database file but all the tables, keys and constraints based on the model. You'll need to be explicit in the model about defining the attributes of properties. The updated designer provides more control over attributes such as StoreGeneratedPattern (e.g., auto-incremented values), foreign key constraints, and cascade deletes. Be aware that running the script against an existing database will overwrite any existing data.

Model-first design in EF4 depends on a combination of a T4 template and a workflow, which makes the generation completely customizable. Look for more information coming from the Entity Framework team on how to customize the generation of your database scripts.

3. Complex Type Support in the Designer
Complex types are an essential element in the EDM. They let you encapsulate a set of fields into a property. Unfortunately, the EF1 designer does not support complex types, which makes it very difficult to work with them. The new designer allows you to define and reuse complex types in your model. In Figure 2, I've selected Customer properties that define a Customer's name, then chose to refactor them into a complex type.

The results of this refactoring are shown in Figure 3. The entity contains the complex type property which, unfortunately, cannot be expanded. But you can see the different properties of Name in the mappings and how they map back to the table columns.

As with EF1, the complex types are available in code when querying and working with the entity objects. 

IEnumerable<Customer> contactsQuery = from c in context.Customers
   orderby c.Name.LastName
   select c; 

The object contains the complex type, as shown in the debug window in Figure 4.

4. New Way of Generating Classes from the Model
EF has traded in the proprietary code-generation API that was part of EF1 for Visual Studio's T4 Code Generator. T4 (Text Template Transformation Toolkit) is a powerful tool that was introduced in VS 2008. With T4, you create code generation instructions by combining T4 syntax with C# or Visual Basic, then link this file to some metadata, such as an .edmx file. T4 will automatically process the template against the metadata and create a new code file based on the output.

EF4 contains a default template that's used to generate classes from the EDM. But you can override this default. The EDM Designer has a context menu option, Add New Artifact Generation Item, which lets you take control of the template so that you can customize it. (Note that the menu option name might change by RTM.) EF copies the template into your project (see the .tt file in Figure 5); then all subsequent code generation from your model will come from this template. By customizing the template, you can take ownership of the definition of the classes that are built based on the model.
5. Support for POCO Objects
EF1 allows you to use your own classes and still benefit from the model, querying, and change tracking. However, your classes still require some tight binding to the EF APIs, either by inheriting from EntityObject or implementing some of EF's interfaces. EF4 removes that constraint. You can now use objects that have no knowledge of the Entity Framework. There are two steps to enabling this Plain Old CLR Object (POCO) support. The first step is to ensure that your class, property names, and types line up with the entity, property names, and types defined in the EDM, as Figure 6 shows. Using the Convention over Configuration pattern, EF will assume that the names line up and use that assumption to work out the relationship between the class and the model.

The second step is to create an ObjectContext class with properties that return the ObjectSets of the classes. ObjectSet is new to EF. In EF1, when you called an EntitySet, such as context.People, it returned an ObjectQuery of entity types. In EF4, the return is an ObjectSet of entity types. The ObjectSet is a variation on an ObjectQuery and is less tightly bound to the query. (ObjectSet gives you another thing to look forward to—easier mocking for unit tests.) This will not only allow you to use LINQ to Entities to construct queries, but it will enable your classes to participate in EF's change tracking. Figure 7 creates the context class, ties it to the model, and wraps the LineItem class as a queryable ObjectSet.

Figure 7: Wrapping the LineItem class as a queryable ObjectSet


    public class AWContext : ObjectContext
        private ObjectSet<LineItem> _lineitems;
        public AWContext()  : base("name=AWLTEntities", "AWLTEntities")
            _lineitems = CreateObjectSet<LineItem>();
        public ObjectSet<LineItem> LineItems
                return _lineitems;


There is much more that you can do once you've set up the proper pattern for using your own classes in EF4. Check the ADO.NET (Entity Framework) Team Blog for a series of posts on POCO with EF4 written in June 2009.

6. Code-Only Support : POCO Classes with No Model
The Entity Framework Feature Pack, which will be released separately from VS 2010, contains support for "code-only" development. This is the most agile way of using Entity Framework. With code-only, you will not even need to create an EDM. EF does rely on the metadata supplied by the model, but the code-only mechanism will create that metadata on the fly based on the existing classes and some additionally provided information. It’s a hugely powerful features for Domain Driven Development and is still evolving.

7. Enhanced Support for Stored Procedures
EF4 Beta 1 includes a number of enhancements for stored procedure support, and Beta 2 promises even more. The one that I'm most happy to see is support for stored procedures that return results that don't match an entity. EF1 only allows you to map READ stored procs that line up with an entity or return a scalar value. Now you can create a complex type and use that as the target of a function that imports a stored procedure into your model.

My database has a stored procedure that returns a name and ID. I can create a complex type in the Model Browser that matches these results, as Figure 8 shows.

Now I can map the stored procedure to the CustName complex type, as shown in Figure 9. The default code generator creates a function of the ObjectContext that lets me easily call this function and materialize objects from the results. 

List<CustName> custs = context.GetNames().ToList(); 

Stored procedures that return scalar values also benefit from the code generator's new ability to call the functions from the ObjectContext. Here's a call to the YearswithSalesGreaterThan function that's mapped to a stored procedure that returns strings. 

IEnumerable<string> salesYears = context.YearswithSalesGreaterThan(5000); 

One other notable improvement to stored procedures in EF4 Beta 1 is in function mapping. When mapping Insert, Update, and Delete stored procedures to entities via function mapping, EF1 required that you map all three. With EF4, you can map only one or two of the functions. Then when you call SaveChanges, the mapped functions will be used where available and Entity Framework will generate commands for modifications that don't have associated functions.

Look for even more support for stored procedures in the Beta 2 and RTM versions of VS 2010.

8. Lazy Loading Support
Developers familiar with ORMs are used to having related data loaded automatically on demand. EF1 does not support implicit loading, although it does have eager loading (with the Include method) and explicit loading with the Load method.

EF4 introduces the ability to instruct an ObjectContext to implicitly load related data on demand using the new ObjectContext.ContextOptions.DeferredLoadingEnabled property. This property is false by default. Once you've set the property to true, EF will implicitly load related data.

By setting DeferredLoadingEnhabled to true, EF will query the database to get the related orders for each Customer. Otherwise, the counts will always return 0. Be aware that if there are 200 customers, lazy loading will mean 200 additional database calls. 

   IEnumerable<Customer> custs = context.Customers;
   foreach (Customer c in custs)

In Beta2, note that DeferredLoadingEnabled will be changed to LazyLoadingEnabled. More importantly, for newly created models, lazy loading wil be enabled by default.

9. Foreign Key Support—Coming in Beta 2
The EDM in EF1 stays true to its inspiration, the Entity Relationship Model, which buries foreign keys in the mappings.  Foreign keys are nowhere to be found in the conceptual model, which became a big source of frustration for many developers. EF4 now supports the ability to create a model with relationships defined with foreign keys as scalar values. In fact, this will be the default when you create a model with the EDM wizard. Querying the model won't change dramatically; however, the exposed foreign keys will make interacting with related objects much easier in many scenarios.  Although the EF team has written about foreign key support on, the feature will not be available until Beta 2.

10. Self-Tracking Entities
Self-Tracking Entities is an important part of the Feature CTP that will relieve the pain many developers have felt when using the EF in services and websites. EF's SaveChanges method relies on change-tracking information (original values and EntityState) to push modifications to the database. But in EF1, the entities know only about their current values. It is the ObjectContext that keeps track of the state information. However, because the context is not serializable, moving that state information across processes is a complicated challenge. In EF4, you have the option of encapsulating the change information within the entities so that information can be carried around with the entities. This makes updates across processes almost effortless.

To create self-tracking entities, you'll use a T4 template provided in the Feature CTP. The resulting classes are POCO classes with no dependency on the Entity Framework. This way, client applications that consume these classes will not need to have a dependency on EF.

Essentially, the new entities keep track of their state—such as Modified or Added. When they come across a process, you can attach them to an ObjectContext without losing that key piece of change-tracking information. Attaching a self-tracking entity to a context will automatically render its state as Unchanged, just like any other entity. However, the CTP has a new extension method for ObjectContext called ApplyChanges that will pull in the entity and, at the same time, fix up its state. 

using (var context = new MyEntitiesContainer())

 What's especially nice is that if the entity you pass in is a graph, it will do the same to all the entities in the graph. There is no comparable function to this when working with regular entity objects and graphs.

11. Model-Defined Functions
EF lets you add custom properties to the model classes that aren't defined in the model. For example, if your database table and entity both contain a FirstName and LastName column, you can create a class-level property, FullName, that concatenates these two fields. The drawback of this is that because the new custom property is not part of the model, you can't use it in either LINQ to Entities or Entity SQL queries. Additionally, if you're sharing your model with another application, you need to share the classes that contain the custom properties as well.

EF4 provides a solution to this: model-defined functions. We now have the ability to define functions directly in the conceptual model. Currently there is no designer support for this, so you would have to input the XML directly.

Here is a model-defined function for the FullName function. It takes a Contact type as a parameter and performs the operation defined in the DefiningExpression tag on that type. 

<Function Name="FullName" ReturnType="Edm.String">
   <Parameter Name="c" Type="TestModel.Contact">
      Trim(c.LastName) + ", " + c.FirstName

It's easy to call in Entity SQL. 

SELECT c.contactId, FullName(c)  FROM MyEntities.Contacts as c 

For LINQ to Entities, you'll have to create a related method in your entity class, and then you can use the function in your query. 

from p in context.People
orderby Functions.FullName(p)
select new \\{p.PersonID, FullName=Functions.FullName(p)\\} 

It's also possible to create model-defined functions to return entities, collections, and other types.

A More Efficient, Accessible Framework
In this article, I've touched on 11 of the enhancements to EF that you'll find in VS 2010 and .NET 4.0. Although these are the most significant improvements to EF4, there are so many other changes, great and small, throughout the designer and the APIs making EF4 a technology that will be much more palatable to a wider audience of developers.

Julie Lerman is a Microsoft MVP, .NET mentor, and consultant. Julie presents on data access and other topics at user groups and conferences around the world, blogs at, and is the author of Programming Entity Framework (O’Reilly Media) and the upcoming second edition. Follow Julie on Twitter at julielermanvt.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.