.NET Entity Framework WTF!? Part One

I’ve been doing a bit of work in C#/.NET using the new .NET MVC framework and the ADO.NET Entity Framework. As a newcomer to the platform as a whole, I was actually pretty stoked about getting started. As I began to get in to my project, I would search the web (StackOverflow.com) when I had issues. As things progressed, I started to realize some of the shortcomings of the entity framework. Overall, I actually found it quite nice to work with. However, the issues that I ran in to became a bit annoying.

The first issue with the entity framework is the lack of lazy loading for relations.With most ORM like setups, you can specify relations to load up front and others will be loaded upon request (lazy loaded). Not so with EF! With the entity framework, you have to explicitly load relationships that you choose not to load up front.

For example. I have a table called [Employee] and a table called [Goal].  The [Goal] has an employee field ([Goal].[Employee]) with a foreign key relation on the `Employee` table.

So to load the employee I had code that looked like

try {
// load a single employee
Employee employee = ent.Employee.Where(e => e.Id == 1).ToList().First();
} catch (Exception exc) {
}

Then at some other point in the code, I would need to get the goals associated to the loaded employee. The Employee object has a field to reference the employee’s goals. So naturally, I thought the code for such an operation would look like this

List<Goal> goals = employee.Goal.ToList();

As it turns out, that was only half the battle. I thought the entity framework would load the goals for that employee and all would be good. Not so. The entity framework wants you to tell it when to load references.

The code now looks something like this

if (!employee.GoalReference.IsLoaded)
{
// load the goals for this employee
employee.GoalReference.Load();
}

List<Goal> goals = employee.Goal.ToList();

A more in depth and passionate post regarding this issue was found here http://reddnet.net/code/ado-net-entity-framework-impressive-powerful-useless/ This article gives a more in depth look at this issue. It is also an excellent example in how to drop the “F” bomb in blog posts.

.NET Entity Framework

Leave a Reply