IQueryable<T> and IUnitOfWork Revisited

So I’m on a pretty cushy government contract (turns out that if you want to have a low stress job in software development, taking a public sector job is the way to go) right now. Microsoft stack all the way down except…Oracle on the backend (*doh*). I have become an EF Code First Zen Master (cutting my teeth on the various CTPs as they were released) and love how well it stays out of my way. My IQueryable<T>/IUnitOfWork combo that I blogged about before have become my bread and butter in creating rich domain models mapped to a database. I was really dreading giving that advantage up. I got approval from the manager to use NHibernate which provides a great LINQ implementation out of the box and decided to try it out using NH.

If you recall, because of the design, the only element of the combo that even cares about persistence is the concrete unit of work implementation. So far I have an InMemoryUnitOfWork (for mocking/testing purposes), and an EfUnitOfWorkBase (that manipulates a DbContext), now I need to make an NhUnitOfWork.

    public class NhibernateUnitOfWorkBase:IUnitOfWork
    {
        private ISession _session;

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

        public void Commit()
        {
            _session.Flush();
        }

        public void Attach<T>(T obj) where T : class
        {
            _session.Update(obj);
        }

        public void Add<T>(T obj) where T : class
        {
            _session.Save(obj);
        }

        public IQueryable<T> Get<T>() where T : class
        {
            return _session.Query<T>();
        }

        public bool Remove<T>(T item) where T : class
        {
            _session.Delete(item);
            return true;
        }
    }

That’s it. I tested it out by making swapping the EfUnitOfWork in Pigskin with this one and configuring the mapping for NHibernate (which for the most part only needed a few explicit configurations). Bada-bing, bada-boom, I’ve switched O/RMs just like that.

Published Wednesday, May 25, 2011 6:43 AM by Mike Brown

Leave a Comment

(required) 
(required) 
(optional)
(required)