nhibernatesessionentity-framework-4objectcontextisession

EF4 ObjectContext vs NHibernate Session


I'm trying to learn some NHibernate after diving into EF4. Is the equivalent of the EF4 ObjectContext (or DbContext) the NHibernate Session?

Specifically, in EF4, you derive from ObjectContext (or DbContext) and your class contains explicit ObjectSet's of each entity, for example:

    public class EcommerceContext : ObjectContext {
        public ObjectSet<Customer> Customers {get; set;}
        public ObjectSet<Product> Products {get; set;}
        // etc.
    }

In the NHib examples I've seen so far, the Session object isn't used this way. Am I missing something?


Solution

  • If you're using NHibernate 3 it's fairly trivial to implement a data context.

    public class YourDataContext
    {
        public ISession Session { get; private set; }
        public YourDataContext(ISession session)
        {
            Session = session;
        }
    
        public IQueryable<Customer> Customers
        {
            get
            {
                return Session.Query<Customer>();
            }
        }
    }
    

    The same thing is possible in NHibernate 2 but slightly different. You will need the NHibernate.Linq library which is in the contrib modules.

    public class YourDataContext:NHibernateContext
        {
            public YourDataContext(ISession session)
                : base(session){}
            public IOrderedQueryable<Customer> Customers
            {
                get
                {
                    return Session.Linq<Customer>();
                }
            }
        }
    

    I'm guessing since you're asking about a datacontext that you're looking to use Linq, and if that's the case, you should definitely use NH3 as the linq provider is much improved.

    It should be noted that a datacontext in EF and a datacontext in NH are going to behave differently because NH does not do objectracking and EF does, among other things. You'll see other differences as you learn about it.