Sunday, 20 June 2010

For anyone that's used WCF Data Services (formerly ADO.NET Data Services), I guess you'll have run into the fact that using the Expand function for eager loading tables referenced by foreign keys uses a string as its overhead parameter:

I was always really confused with this. This is what it's like in Entity Framework 4.0 as well with the Include function. Using a string literal of course means that schema changes will not be picked up at compile time. The code will successfully be compiled if the "Wheels" table has changed its name for instance, and the problem only gets picked up in the testing phase.

A type safe approach

So here's the code that I use. It's an extension class, so you can carry on using your existing data context object, and is not overtly "code-intrusive". It provides the ability to use strongly typed expressions instead of magic strings. When your schema changes, a compile error will be raised displaying that the foreign table name is no longer correct. This will of course make an automated build fail, which is exactly what we want.