Archive

Posts Tagged ‘DynamicObject’

Leveraging DynamicObject in .Net 4

March 24, 2011 4 comments

or, how I added ActiveRecord-style find_by_* to Rob Conery’s Massive data access class.

When Rob Conery first announced Massive, I was really interested in how he was leveraging the new dynamic capabilities in .Net 4 to create a more “Ruby-esque” experience for .Net developers.  Massive allows you to easily query a table in a database for information and returns back an ExpandoObject with a property for each column in your resultset.  So, instead of your typical:

while (dataReader.Read()) {
obj.Property1 = dataReader[“Field1”];

}

you can instead do:

var data = table.All(“where id = 1”);

foreach (var row in data) {
obj.Property1 = row.Field1;
}

I thought this idea was pretty darn awesome, but there was something that bothered me about it – you see that “where id=1” in there – yea, I thought you did.

Wouldn’t it be nice if you could do something like this instead:

var data = table.FindBy().Id(1);

foreach (var row in data) {
obj.Property1 = row.Field1;
}

Well, if you grab my fork of Massive (or convince Rob to take my pull request – hint 🙂 ) you can.

Just head over to https://github.com/jeetkundoug/massive and take a look.

Originally I had DynamicModel deriving from DynamicObject, which would have meant you could have done something like:

table.FindById(1);

Which would be nice.  However, it meant that you lost all intellisense on your model, which didn’t seem like a reasonable tradeoff.  So, FindBy() returns an instance of the “Finder” class, which does derive from DynamicObject.  You can pass a few named parameters to FindBy() methods other than just the values for your fields, which allow you to control the order of the data and the columns returned.  See the updated README.markdown for more information.

If nothing else, this was a really interesting intelectual exercise in how you may be able to leverage DynamicObject in C# in some fun and interesting ways.  Also, I got to play around with git and GitHub (I’ve been a Mercurial person mostly to date) – so good stuff all around.

Categories: .Net Tags: , ,