Attaching Disconnected Entities in NHibernate Without Going to the Database

Because the SaveOrUpdateCopy method of ISession is marked as obsolete, we no longer have an API method that allows us to attach a disconnected entity (meaning: coming from a session that no longer exists) to a new session without going to the database, something that Merge, Lock, Refresh all do. Sometimes this is not desirable.

One thing I love about NHibernate is how extensible it is! It was a piece of cake to build this extension method:

   1: public static T Attach<T>(this ISession session, T entity, LockMode mode = null)
   2: {
   3:     mode = mode ?? LockMode.None;
   4:  
   5:     IEntityPersister persister = session.GetSessionImplementation().GetEntityPersister(NHibernateProxyHelper.GuessClass(entity).FullName, entity);
   6:     Object[] fields = persister.GetPropertyValues(entity, session.ActiveEntityMode);
   7:     Object id = persister.GetIdentifier(entity, session.ActiveEntityMode);
   8:     EntityEntry entry = session.GetSessionImplementation().PersistenceContext.AddEntry(entity, Status.Loaded, fields, null, id, null, LockMode.None, true, persister, true, false);
   9:     
  10:     return (entity);
  11: }

A simple example:

   1: Product product = null;
   2:  
   3: using (ISession session = sessionFactory.OpenSession())
   4: {
   5:     product = session.Query<Product>().First();
   6: }
   7:  
   8: using (ISession session = sessionFactory.OpenSession())
   9: {
  10:     session.Attach(product);
  11:  
  12:     product.Price = 34230;
  13:  
  14:     session.Flush();
  15: }

                             

1 Comment

Add a Comment

As it will appear on the website

Not displayed

Your website