Monday, July 27, 2009

The Entity Framework really needs a generic table fetch method

For those of you only marginally familiar with the entity framework, the top object in the system is the DataContext object. Visual Studio will generate a sub class of the base type DataContext for you, and it does so based on your SQL database model. In the end, you get subtype filled with types that look like your SQL tables. You query from this schema. You could use Linq. You could use the fetching methods associated with Entity Framework.

So here is the rub. When you are working on a Model-View-ViewModel app, you need to write a lot of redundant boilerplate code for each one of your EF framework objects. The code is absolutely identical save for the EF framework class type. The type varies. You may need a Model class for customers class. You may need one for Institutions class. You may need one for Products class. I can go on. A close examination of all three of these model classes will indicate that they are identical, save for the type.

This is the perfect moment for the use of Generics. You should write a generic model class and pass in the type parameter. BANG! You have just created the universal model class.

Guess what? You get fucked in the ass (savagely) if you try to do this. When you attemp to write this generic model class: BANG! You run smack into one brick wall. Your DataContext cannot be type parametrized in a generic fashion. Suppose I have written the following code:

var db = new IndirectEntities(); // This is my DataContext

I cannot subsequently write the following code.

/* Psudeo code, my fucking blog engine screws with angle brackets */
var QueryResult = from r in db.Table(of Customer) select r;

Believe it or not, this will stop you cold, frustrate the hell out of you, and stymie your progress. Without the ability to fetch the table collection by generic type param, nothing follows. You cannot construct an operational generic model class without this missing feature. If the Entity Framework were at all friendly to the use of generics, it would be totally possible, and highly effective. Unfortunately, the EF basta... errr... gentlemen did not perceive any use in supporting generics.

I have been probing Google all day looking for a solution. It would appear that Microsoft left this function out of the entity framework. Perhaps it seemed a trifle too dynamic for their tastes. Many people seem to have busted their skulls on this issue. So far, no solution. Some have suggested using nHibernate, although I am not sure that is a solution.

So, here I sit, redundantly cranking out the the same fucking boilerplate code over and over again, when one generic class would have killed the bitch outright. Of course, this is where a code generator would be good, but I should not have the need to set one up. A generic class should have shot this problem down.

Double dumb ass on the Entity Framework team. You just weren't thinking there were yah?