Home > C#, Magiq > Magiq: Named scopes in C#

Magiq: Named scopes in C#

Some weeks ago, my friend Jonas told me about Ruby’s ActiveRecord Named scopes and I thought what a marvelous feature! Later, I realize that it can be implemented in c# using Magiq.

Suppose you have a store that sells products and these products has expiration date. You call “Available” the products that had not yet expired. In order to find the not expired products, we could do, using Linq:

var availableProducts = store.Products.Where( x => x.ExpirationDate > DateTime.Now );

The problem with this approach is that the more time passes, more products the store will have and more expired, so it could retrieve the entire products collection just to filter some. Magiq to the rescue!

var availableProducts = store.Products.Query( x => x.ExpirationDate > DateTime.Now );

As I told in a previous post, it will generate a new sql query with the new condition.

Ok. In a perfect world, you will have something like an AvailableProducts property in the Store class, because the availability definition could change in the future.

public IEnumerable<Product> AvailableProducts {
    get {
         return Products.Query( x => x.ExpirationDate > DateTime.Now );
        }
    }
}

Now, what happens if besides store, we have a warehouse full of products and we need the available products from there? We will have add the same method in the Warehouse class.

Wouldn’t be nice if we could do it this way:

var availableProductsFromStore = store.Products.Available();

var availableProductsFromWarehouse = warehous.Products.Available();

Ok, we can 🙂

public static class ProductNamedScopes
{
	public static IEnumerable<Product> Available( this IEnumerable<Product> self )
	{
		return self.Query( x => x.ExpirationDate > DateTime.Now );
	}
}

I know, this could be implemented using pure linq, a foreach, ado.net, NHibernate’s collection filtering, etc. But Magiq let you hide all that stuff and use pure Linq in a generic way.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: