Categories
.net 3.5 LINQ LLBLGenPro VS 2008

Using extension methods to make code less cluttered

Here is an example where an extension method is useful. Take this [LGP] code for example:

public EntityCollection<CustomersEntity> GetCustomers() { using (DataAccessAdapter da = new DataAccessAdapter("Data Source=[SERVER];Initial Catalog=Northwind;Integrated Security=True")) { LinqMetaData context = new LinqMetaData(da); var q = from c in context.Customers select c; EntityCollection<CustomersEntity> result = ((ILLBLGenProQuery)q).Execute<EntityCollection<CustomersEntity>>(); return result; } }

It is a simple LINQ to LLBLGenPro select against (we all love) Northwind database. Pay attention at result assignment. To have data returned as a native [LGP] EntityCollection you have to resort to ILLBLGenProQuery interface. You have to use ILLBLGenProQuery.Execute method on IQueryable<T> q. A cast is obviously required because IQueryable<T> doesn’t know anything about ILLBLGenProQuery. While this code works it is not exactly elegant – I am referring to the later cast of course.

So, the idea is to have something like this instead:

EntityCollection<CustomersEntity> result = q.Execute<EntityCollection<CustomersEntity>>();

Possible? Sure, just add this static class with a single extension method and you are good to go:

public static class Tubular { public static TResult Execute<TResult>(this IQueryable q) where TResult : IEntityCollection2 { return ((ILLBLGenProQuery)q).Execute<TResult>(); } }

Or perhaps, we can further reduce the cluttering by introducing this extension method:

public static class Tubular { public static EntityCollection<TEntity> Execute<TEntity>(this IQueryable q) where TEntity : EntityBase2, IEntity2 { return ((ILLBLGenProQuery)q).Execute<EntityCollection<TEntity>>(); } }

to achieve this, even less cluttered, line:

EntityCollection<CustomersEntity> result = q.Execute<CustomersEntity>();

Isn’t this or former de-cluttered line more readable and more elegant than the original?

3 replies on “Using extension methods to make code less cluttered”

Leave a Reply