Welcome to RightHand's community place Sign in | Join | Help

Using extension methods to make code less cluttered

Here is an example where an extension method is useful. Take this LLBLGen Pro 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 LLBLGen Pro 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?

Published 8. november 2008 15:09 by Miha Markic

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Using extension methods to make code less cluttered

14. november 2008 21:56 by Bojanv
Guess, they didnt thought on that :)

# re: Using extension methods to make code less cluttered

17. november 2008 21:52 by Milan Negovan
Miha, why not take it a step further and introduce q.GetCustomers()? You're the end-consumer of this API, so make it easier on yourself. :)

# re: Using extension methods to make code less cluttered

18. november 2008 11:30 by Miha Markic

Hi Milan,

Indeed, the options of "getting lazy" are endless :-)

Leave a Comment

(required) 
required 
(required)