<< back to blog

Shorthand Repository Accessors

nhibernate ~ .net ~ ddd

17 Mar, 2009

Today I was helping a friend with an NHibernate app, and noticed an opportunity to shorten some Repository code.

Here’s an example…

[Test]
public void Should_Find_Tag_By_Name()
{
   // find some tags
   var tags = new TagsRepository();

   var cool = tags.FindByName("cool");
   var hot = tags.FindByName("hot");
   var cold = tags.FindByName("cold");

   // assert some stuff...
   Assert.AreEqual("cool", cool.Name); 
}

This FindByName isn’t bad, but a shorter version is possible.

[Test]
public void Should_Find_Tag_By_Name()
{
   // find some tags
   var tags = new TagsRepository();

   var cool = tags["cool"];
   var hot = tags["hot"];
   var cold = tags["cold"];

   // assert some stuff...
   Assert.AreEqual("cool", cool.Name); 
}

See the difference? I quite like this syntax for name-based lookups. Implementing it is really easy.

public class TagRepository
{
   public Tag FindByName(string name)
   { 
      return (from t 
                 in UnitOfWork.Session.Linq<Tag>() 
                 where t.Name == name select t)
                 .FirstOrDefault();     
   }

   public Tag this[string name]
   {
      get{ return FindByName(name); }
   }

   public Tag this[long id]
   {
      get{ return UnitOfWork.Session.Get<Tag>(id); }
   }
}

Notice that I’ve also added a method that allows you to load a Tag by ID, using the following syntax:

var tagToLoad = long.Parse( Request["tagId"] );
var tags = new TagRepository();
var tag = tags[tagToLoad];

Anyone seen this approach used already?

You may also like...
.NET Gem Fun
Automating .NET development (and NHibernate) with IronRuby + Rake
Get a Rails-Stylee Interactive Shell For Your NHibernate Backed Domain Model
In Memory SQLite Testing with NHibernate
NHibernate Trick
NHibernate: Calling Update Unnecessarily
.NET Config for Multiple Developers
NHibernate in Action 2nd Edition - Your Opinion
Shorthand Repository Accessors
NHibernate for Ruby?

kick it on DotNetKicks.com
blog comments powered by Disqus