为什么在IPersistenceContext.UnproxyAndReasociate之后IPersisteneCon

本文关键字:之后 IPersisteneCon UnproxyAndReasociate IPersistenceContext 为什么 | 更新日期: 2023-09-27 18:23:46

我有一个与NHibernate会话断开连接的代理,我正在尝试查看它是否在第二个会话中被修改。在这个过程中,我检查实体是否是代理,如果是,则执行以下调用:

 var proxy = entity as INHibernateProxy;
 var obj = persistenceContext.UnproxyAndReassociate(proxy);
 var oldEntry = persistenceContext.GetEntry(obj);

在这一点上,我希望oldEntry不会为null,因为代理和底层实体已经与persistenceContext重新关联。但是,UnproxyAndReassociate不会用实体填充StatefulPersistenceContext.entityEntries映射。

为什么不呢?重新关联难道不被视为负载吗?

为什么在IPersistenceContext.UnproxyAndReasociate之后IPersisteneCon

如果您查看UnproxyAndReassociate:的实现

public object UnproxyAndReassociate(object maybeProxy)
{
    var proxy = maybeProxy as INHibernateProxy;
    if (proxy != null)
    {
        ILazyInitializer li = proxy.HibernateLazyInitializer;
        ReassociateProxy(li, proxy);
        return li.GetImplementation(); //initialize + unwrap the object 
    }
    return maybeProxy;
}

它似乎重新关联了代理,并且您可以取回未装箱的对象。ReassociateProxy会:

private void ReassociateProxy(ILazyInitializer li, INHibernateProxy proxy)
{
    if (li.Session != Session)
    {
        IEntityPersister persister = session.Factory.GetEntityPersister(li.EntityName);
        EntityKey key = new EntityKey(li.Identifier, persister, session.EntityMode);
        // any earlier proxy takes precedence
        if (!proxiesByKey.ContainsKey(key))
        {
            proxiesByKey[key] = proxy;
        }
        proxy.HibernateLazyInitializer.Session = Session;
    }
}

因此它被存储在字典proxiesByKey中。

public EntityEntry GetEntry(object entity)
{
    return (EntityEntry)entityEntries[entity];
}

GetEntry甚至不考虑proxysByKey,因此重新关联代理与重新关联基础条目与会话不同。