Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the entity type on an object that may be a NHibernate proxy object?

Tags:

nhibernate

I have a base class DomainObject for all my business objects I am using with NHibernate. It contains the Id property.

public abstract class DomainObject
{
    public virtual int Id { get; private set; }
}

I would like to write an IEqualityComparer to compare my domain objects. If two objects have the same Id and are the same kind of object they should be equal. However when I use GetType() to get the type of the object, it will return the NHibernate proxy type. So this code:

bool IEqualityComparer.Equals(object x, object y)
{
    // null checking code skipped here
    if(x is DomainObject && y is DomainObject)
    {
            return ((DomainObject) x).Id == ((DomainObject) y).Id
                    && x.GetType() == y.GetType();
    }
    return x.Equals(y);
}

Doesn't work correctly, because the type of x is Asset but the type of y is AssetProxy21879bba3e9e47edbbdc2a546445c657.

So, how do I get the entity type on an object that may be a NHibernate proxy object? i.e. in the example above Asset instead of AssetProxy21879bba3e9e47edbbdc2a546445c657?

like image 354
Jeff Walker Code Ranger Avatar asked Sep 20 '10 21:09

Jeff Walker Code Ranger


1 Answers

You can get the real type of a proxy with:

NHibernateUtil.GetClass(x);

or you can add a method to DomainObject like:

public virtual Type GetTypeUnproxied()
{
    return GetType();
}

Which is really slick and doesn't depend directly on NHibernate.

Alternatively, one can approach the problem by saying you need to get the true object, rather than the proxy, which, if the session is handy, can be done with:

session.PersistenceContext.Unproxy(x);

As mentioned in another answer, if you're trying to implement equals it would be a good idea to check out the Sharp architecture implementation of Equals.

like image 198
Jeff Walker Code Ranger Avatar answered Oct 24 '22 16:10

Jeff Walker Code Ranger