如何获得可能是NHibernate代理对象的对象上的实体类型? [英] How do I get the entity type on an object that may be a NHibernate proxy object?

查看:64
本文介绍了如何获得可能是NHibernate代理对象的对象上的实体类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于与NHibernate一起使用的所有业务对象,我都有一个基类DomainObject.它包含Id属性.

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; }
}

我想写一个IEqualityComparer来比较我的域对象.如果两个对象具有相同的Id并且是相同类型的对象,则它们应该相等.但是,当我使用GetType()获取对象的类型时,它将返回NHibernate代理类型.所以这段代码:

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);
}

无法正常工作,因为x is Asset的类型是y is AssetProxy21879bba3e9e47edbbdc2a546445c657的类型.

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

那么,如何获取可能是NHibernate代理对象的对象上的实体类型?即在Asset而不是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?

推荐答案

您可以通过以下方式获取代理的真实类型:

You can get the real type of a proxy with:

NHibernateUtil.GetClass(x);

或者您可以向DomainObject添加方法,例如:

or you can add a method to DomainObject like:

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

这真的很漂亮,并且不直接依赖于NHibernate.

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.

这篇关于如何获得可能是NHibernate代理对象的对象上的实体类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆