entity framework

What's New in Entity Framework 5.0?

In this blog post, I will be talking about the difference between Entity Framework 4.0 and 5.0. I hope you find it informative and enjoyable.

Agenda (Click to jump)

Performance optimizations
Enum support
Spatial data types
Code first improvements
DbContext generation
Multiple diagrams per model
Table-valued functions
Batch import of stored procedures

Performance Optimizations

For years, I have been working with various platforms and languages, utilizing different data access technologies – from JDBC to ADO.NET and Entity Framework. Back in the days when I was a Java developer working with Hibernate, writing my own XML mapping configuration (no Generate from Database option), there is one question that is still valid today. What's the catch? We have automatic configuration, generation, and mapping. We have LINQ to Entities doing all the work for us including generating the SQL and allowing us to use the build-in CLR functionality in order to produce working queries relatively easily. So really, what's the catch?

Well, you saw the title of the section.

The main problem is that all of this goodness comes with a price in terms of performance. All object relational mappers produce a well-known overhead and many companies, which require high-performance applications, ask themselves: “Is it worth it? Is it too slow or too heavy?”

The answer? Yes, it is. But that's why we, the engineers, are here - to make it work faster and keep the benefits measured in production time. If you just install Entity Framework (EF) and start it, you'll need to make a refactor sooner or later.

Getting straight to the point, Entity Framework 5.0 uses the so-called "auto-compiled" queries feature which compiles (read "translates") the Entity SQL or LINQ to Entities expression tree in a pure SQL (or T-SQL) code. In order to do some accurate measurements, we need to get few things straight:

  1. Don't look at the very first query sent. During that query, the framework "warms up" and configures the views and all other components it needs.
  2. Next, don't look at the first invocation of a given query. During that time, EF caches parts of the query, so the subsequent calls can be faster. This doesn't mean the query is compiled. It's not...yet.
  3. Take into consideration that .NET 4.5 is an "in-place" upgrade, meaning that once it is installed, you will not have any indications that the new version is actually installed (no GAC folder, no 4.5 assemblies, no registry entry). You also can’t go back to .NET 4.0 so even if you target 4.0 in project properties, it will still use the 4.5 run-time.

I've run a few performance tests here. I created a slow query (few joins, dozens of filters, and ternary operators) and measured its performance via .NET 4.0 with Entity Framework 4.0 (on another machine, of course), and .NET 4.5 with Entity Framework 5.0.

The results (tested with 4 core CPU and 8GB of RAM, Windows 7, and SQL Server 2008):

  • Without auto-compiled query - 40ms
  • With auto-complied query - 10ms
  • With manual use of the CompliedQuery class - 5ms

You are going to get some out-of-the-box performance benefits by simply installing EF5 and .NET 4.5. If you want faster query generation, use the CompiledQuery class instead, but be prepared to change your current DAL architecture to support this.

Enum Support

There is a support for enumerations in EF 5.0. In order to activate it, create a scalar property of structure Int32 in the .edmx, right-click on it, and select “Convert to Enum”.

Convert to Enum

This creates an Enum, which, upon DDL generation, is translated into a simple column of type Int. This feature provides additional abstraction and integrity constraint in the DAL layer, but from a database point of view, there is no way to find out what a given value in a table really means. You will need to check the project code for that.

Spatial Data Types

Another interesting feature is the support of spatial data types in SQL server. For those who are not aware of them, these types are geography and geometry related classes which allow us to work directly with such data inside the SQL Server (like geographic locations or geometrical representation of something). Below are the related available CLR types. The blue boxes are concrete classes.

spatial data types

There is also a built-in spatial result view in SQL Server, which looks like this:

It is actually quite impressive. For example, if you have a table with points (longitude and latitude) of office locations, you can visualize them directly in SQL Server. You can also utilize a number of functions such as calculating the distance between two points. With EF 5.0 , we can do it in C# (or any CLS supported language for that matter). Note that there are still too few resources on the internet related to this feature, so prepare to dig if you plan to use it.

Code First now works with LocalDB

The Entity Framework Code First approach now works with LocalDB. For those of you who haven’t heard about LocalDB, think of it as a hybrid between SQL Server Express and SQL Server Compact. It runs in a child-process, rather than in a full-blown Windows service. It’s the default Visual Studio 2012 development server, and it’s meant to be light and easy to configure.

DbContext is now the default generated context

DbContext is nothing new. A wrapper around ObjectContext, generated with the help of T4 templates, utilizing the convention-over-configuration principle with POCO classes. It generates something like this:

And the entities look like this:

As you can see, we are talking about pure POCO classes here, but that doesn’t mean that we are actually working with these simple classes at run-time.

Multiple diagrams per model

The new Visual Studio 2012 designer supports multiple diagrams per model. We all know how big models are maintained. Huge databases can quickly become unmanageable without the use of the proper tools.

Here is a screenshot of the standard designer screen in Visual Studio 2012. You can see multiple diagrams on the upper right-hand corner. On the context menu you can select “Move to new Diagram” or “Include” related, which will include all entities with relations to the selected one. You can also change the color if you want.

Table-valued functions

Table-valued functions are also not new in SQL Server, but until now there was no built-in support in Entity Framework. For those of you who are not familiar with these type of functions, they are somewhat of a hybrid between a view and a stored procedure. They support procedural code inside parameters, but can be called from a SELECT statement. They return a single value, but this value is actually a table. This means that it can be chained in a LINQ-to-Entities query.

Here is a simple DDL script for a table-valued function in SQL:

CREATE FUNCTION [dbo].[GetCategories]()
RETURNS TABLE
RETURN
SELECT [CategoryID],
,[CategoryName]
,[Description]
,[Picture]
FROM [dbo].[Categories]

which can be used in LINQ-to-Entities like this:

Batch import of stored procedures

The last feature I want to mention is the ability to import a batch of stored procedures/functions into the .edmx model. Not much to write about here as it’s a matter of click-and-go.

What about Entity Framework 6.0?

Actually, the alpha version of Entity Framework 6.0 is now available in NuGet. You can download it if you like.

http://nuget.org/packages/entityframework

Here is a list of pre-announced features:

Task-based Async - Allowing EF to take advantage of .NET 4.5 async support with async queries, updates, etc.
Stored Procedures & Functions in Code First - Allow mapping to stored procs and database functions using the Code First APIs.
Custom Code First Conventions - Allowing custom conventions to be written and registered with Code First.

That is all from me. I hope you learned something new!

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">