Logo

NHibernate

The object-relational mapper for .NET

Using the new Linq to NH Provider and migrating from the old one

Using the new Linq provider is pretty simple. It all hangs of a Query() extension method on ISession, so you can do things like the following:

  from c in session.Query<Customer>() select c

In my tests, I've tended to wrap the session.Query() call behind a simple facade, along the lines of:

  public class Northwind
  {
   private readonly ISession _session;

   public Northwind(ISession session)
   {
   _session = session;
   }

   public IQueryable<Customer> Customers   { get { return _session.Query<Customer>(); }
  }

Of course, that's entirely optional, but I find the resulting code easier to read:

  from c in db.Customers select c

Once you know how to hook into the session (which as you can see is pretty simple), the rest is just straightforward Linq code, and entirely up to you! Right now I'm not exposing any extension points, but they'll be coming soon (plus another post to describe how to use them).

The version 1 provider used an ISession extension method call Linq() to provide its hook. I purposefully used a different name, since there's no reason at all why you can't use both providers within the same project or, indeed, within the same session. So that gives a couple of migration options for folk that want to move to the new provider:

  • Leave all your current queries using .Linq(), and start using .Query() for new ones.

  • Start changing existing queries from .Linq() to .Query(), just by changing them or by a simple search & replace. The rest of the expression will (hopefully!) just work.

  • Drop your reference to the original Linq provider assembly, and create your own extension method:

      public static IQueryable<T> Linq<T>(this ISession session)
      {
        return session.Query<T>();
      }


    This lets you switch to the new provider without changing a line of your code - and if you find it all goes to hell, you just re-add the V1 reference and comment out your extension method. Should work like a treat.

Other than that, I don't think there's much to tell - usage really should be pretty simple. Oh, one thing that springs to mind - although you can use the V1 provider and the new provider within the same project (or session), don't try to compose queries from them together; that's really going to do weird stuff!


Posted Wed, 16 December 2009 01:52:39 PM by srstrong
Filed under:

comments powered by Disqus
© NHibernate Community 2024