With lazy loading configured, I run into an issue regarding object comparison. My overriden Equals-method within each domain entity class contains the following line:
if (obj == null || !obj.GetType().Equals(GetType()))
Obviously, The type comparison will fail as obj is a proxy instance. I’ve already seen some NHibernate-snippets which unproxy an object and return the real instance. But as I enforce a domain driven design, I do not want any ORM-specific code within my domain layer.
I also cannot unproxy the instance on caller side [e.g. foo.Equals(Unproxy(bar))] as the caller is my application layer which also doesn’t contain any ORM-specific code (all NHibernate dependencies are injected by Windsor).
Long story short: is there any generic code to get the real instance?
The way to solve that is to do a cast:
The cast works because the
proxyinherits from your class (e.g.PersonProxy : Person)The null check is unnecessary as the
ascast will just return null ifobjis either null or not an object that can be cast as a person.