mbue
mbue

Reputation: 1632

NHibernate lazy loading and object comparison

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?

Upvotes: 3

Views: 1274

Answers (2)

cremor
cremor

Reputation: 6876

Alternatively you could create a GetTypeUnproxied method like shown here: https://github.com/sharparchitecture/Sharp-Architecture/blob/master/Solutions/SharpArch.Domain/DomainModel/BaseObject.cs

This method would even work with inheritance mapping since it returns the real type of the object that is inside the proxy.

Upvotes: 3

Trevor Pilley
Trevor Pilley

Reputation: 16393

The way to solve that is to do a cast:

public class Person
{
    public int Id { get; set; }

    public override bool Equals(object obj)
    {
        var person = obj as Person;

        if (person == null)
        {
            return false;
        }

        return person.Id == this.Id;
    }
}

The cast works because the proxy inherits from your class (e.g. PersonProxy : Person)

The null check is unnecessary as the as cast will just return null if obj is either null or not an object that can be cast as a person.

Upvotes: 5

Related Questions