5

Is there a way to make nhibernate return my class instead of its proxy class? I dont mind if it's not lazy or cant be updated.

ryudice
  • 36,476
  • 32
  • 115
  • 163

6 Answers6

12

You can unproxy class with this code

session.PersistenceContext.Unproxy(proxiedInstance)
Sly
  • 15,046
  • 12
  • 60
  • 89
  • 12
    Is there a way to unproxy all associations as well? It unproxies my main object but its relations to other object keep proxied. – ryudice Mar 28 '11 at 20:43
2

You can use following code to get real object

InstanceType instance;
if (proxiedInstance is INHibernateProxy)
{
 var lazyInitialiser = ((INHibernateProxy)proxiedInstance).HibernateLazyInitializer;
 instance = (InstanceType)lazyInitialiser.GetImplementation();
}
William
  • 141
  • 5
2

You should define this in your mapping, by defining lazy="false"

<class name="MyEntity" table="MyTable" lazy="false">
</class>
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
0

I'm using AutoMapper to achieve something similar in Entity Framework.

var nonProxiedInstance = Mapper.DynamicMap<YourType>(proxiedInstance);

That would work if you do not have navigation properties. Otherwise, you'll need to configure a mapping to ignore those properties.

Note: This is (obviously) an inefficient solution.

Ed Chapel
  • 6,842
  • 3
  • 30
  • 44
  • 2
    This doesn't work. The proxy doesn't contain the properties of the inherited (real) class, so it would be missing in the mapped type as well. – Stefan Steinegger Mar 28 '11 at 08:12
0

You can use the technique described in http://sessionfactory.blogspot.com/2010/08/hacking-lazy-loaded-inheritance.html (you'll need to do it recursively)

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
0

session.PersistenceContext.Unproxy(proxiedInstance) will not unproxy the associations. Also the no-proxy lazy loading does the same thing. Disabling lazy loading is not a good idea and AutoMapper would navigate all the properties and trigger the loading mechanism.

IUnitOfWork.Unproxy from the NHUnit package could be used to unproxy the object and it's relations. This method will not initialize any proxy objects by mistake.

  • What specifically is "none of the above"? That comment doesn't work when people submit in new answers. You should specify what techniques won't work and why. – Shiv May 27 '21 at 00:00