How would you check car.Finish.Style.Year.Model.Vendor.Contacts.FirstOrDefault(c=> c.Id == c.Id).FullName for null? :-)

Monday, August 9, 2010

Last week I blogged about how to create a strongly-typed property path ObjectQuery(T).Include with expression-trees.Not that I am the big expression tree agriculturist, no, not at all, I just discovered how powerful expression trees are and that it's a whole typed programming-language! Anyway, today I was facing another interesting issue where I had to reach a long path of objects and a part of it can be null. Consider these classes:Public Class Customer  Public Property Orders As List(Of Order)End ClassPublic Class Order  Public Property Id As StringEnd Class Say  I have a Customer variable (that might also be null itself), and I want to access its first (if available) Order's Id proprety with some string formatting (read note bellow). Normally I would have...

Say goodbye to the hardcoded ObjectQuery(T).Include calls

Friday, August 6, 2010

When you want to eagerly-load navigation-properties with ADO.NET Entity-Framework, you use the ObjectQuery(T).Include method, which takes one argument 'path' typed String. I often find myself changing my database and model by adding / removing / renaming properties or other fields, and I don't realize that an exception thrown in one lonesome window is because of thes changes, all because only hard-coded strings are supported! So I decided to make my own Include implementation, and thanks to Extension Methods, it's hell of a lot easier to use. So, in order to enjoy the 'easycoded' Includes, just copy this module onto your solution and your ready to go:   Imports System.Reflection Imports System.Data.Objects Imports System.Linq.Expressions Imports System.Runtime.CompilerServices <HideModuleName()> Public Module ObjectQueryExtensions   ''' <summary>   ''' Specifies the related objects to include in the query results.   ''' </summary>   ''' <typeparam name="TSource">The entity type of the query.</typeparam>   ''' <typeparam name="TResult">The type of the value returned by selector.</typeparam>   ''' <param name="query">A <see cref="System.Data.Objects.ObjectQuery(Of T)"/>.</param> ''' <param name="path">The include path.</param>   ''' <returns>A new <see cref="System.Data.Objects.ObjectQuery(Of T)"/> with the defined query path.</returns>   ''' <exception cref="ArgumentNullException">query is null.</exception>   ''' <exception cref="ArgumentException"> ...