Hanalei, Hawaii

As I wrote my last post about bringing some ActiveRecord love to C#, something wasn’t sitting right. It was a feeling of “ME-TOO” and I hate that. C# isn’t Ruby - but it can be as expressive given the new constructs. I like the ActiveRecord_Style_Of_Querying, but I know that it’s very Ruby-ish - not very C#-ish. So I changed that.

Damn You Skeet

In Oslo I when I demoed my little ActiveRecord prototype, Jon Skeet was in the audience and was making “I hate dynamics” faces at me from the front row. I tried to kick him a few times as I walked by - but he’s Jon Skeet and you don’t want him heckling you when you discuss anything C# related.

So - true story - he wrote up a query interface that he wanted to see instead, and before the talk was over Jon yelled out “check your email”. Just like that - we have a nice, clear syntax for dynamic querying:

dynamic db = new Products();
db.FindBy(CategoryID:8,UnitPrice:100);

Rather than splice out the method call, just use named arguments (as others have suggested as well). It reads well, it’s clear and it’s very C#.

The code is up here if you want to have a look. Alas I’ve pushed over 450 lines… but I think it’s worth it.

I’ve also added some hooks for order by and column specification:

dynamic db = new Products();
db.FindBy(CategoryID:8,UnitPrice:100, OrderBy:"ProductID DESC", Columns:"ProductName"); 

First, Last

I mentioned in my last post that I would get to First, Last etc and I’ve done that here. You can use this syntax with First, Last, or Get and you’ll get one record back. OrderBy what you want - or the default is ordering by PK:

dynamic db = new Products();
db.First(CategoryID:8,UnitPrice:100, OrderBy:"ProductID DESC", Columns:"ProductName");

Or, if you prefer your queries typed with Lambdas - there’s always EF.

Blog comments powered by Disqus

My name is Rob Conery and I am the owner/smooth operator of Tekpub, creator of
This Developer's Life, and an avid Ruby/Rails/.NET developer.

Find Something