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

后端 未结 4 876
独厮守ぢ
独厮守ぢ 2021-02-19 04:21

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

public abstract          


        
相关标签:
4条回答
  • 2021-02-19 05:04

    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.

    0 讨论(0)
  • 2021-02-19 05:06

    i took a different aproach in a production project. I simply have a global HiLow Id-Generator which generates Id's unique for all types then i can:

    // in DomainEntity
    public override bool Equals(object obj)
    {
        var other = obj as DomainEntity;
        if (Id == 0) // IsTransient()
            return ReferenceEquals(this, other);
        else
            return (other != null) && (Id == other.Id);
    }
    
    // Comparer
    bool IEqualityComparer.Equals(object x, object y)
    {
        return object.Equals(x, y);
    }
    
    0 讨论(0)
  • 2021-02-19 05:08

    You can implement a backdoor property as described here to get the actual nonproxied instance.

    0 讨论(0)
  • 2021-02-19 05:11

    To get real object instead of proxy you can use

    session.PersistenceContext.Unproxy(proxyObject)
    

    But I think you should look at Sharp architecture implementation for Equals.

    0 讨论(0)
提交回复
热议问题