NHibernate,代理和平等 [英] NHibernate, proxies and equality
问题描述
我正在使用NHibernate 3.3.1,发现了一个非常有趣的问题. 在我的域模型中,我定义了两个类:Carriage和CarriageRequest,它们相互引用.因为延迟加载已打开,所以当我访问carry.CarriageRequest时,它指向一个代理对象.好的,可以.但是,当我调用CarriageRequest类中定义的任何方法时,"this"将引用第三个对象实例.
I'm using NHibernate 3.3.1 and found very interesting problem. In my domain model I defined two classes: Carriage and CarriageRequest, referencing each other. Because lazy loading is turned on, when I access carriage.CarriageRequest - it points to a proxy object. That is okay. But when I invoke any method, defined in CarriageRequest class, 'this' references to a third object instance.
示例:
class CarriageRequest
{
public virtual void Test(CarriageRequest instance)
{
Debug.WriteLine(Object.ReferenceEquals(this, instance)); // prints FALSE
}
}
class Carriage
{
public virtual CarriageRequest CarriageRequest { get; set; }
}
...
var carriage = session.Get<Carriage>(123);
carriage.CarriageRequest.Test(carriage.CarriageRequest);
因此,看起来NHibernate代理包装原始对象并将所有方法调用转发到包装对象.在这种情况下,如何使用"=="? 我需要做这样的事情:
So it looks like NHibernate proxies wrap original objects and forward all method invocations to wrapped objects. How can I use "==" in this case? I need to do something like this:
var shipment = (from sh in Carriage.Shipments where sh.CarriageRequest == this & sh.Warehouse == waybill.Warehouse select sh).FirstOrDefault();
此代码在代理对象内内部执行,所以'shipment'始终为null,因为'sh.CarriageRequest == this'始终为false.因为sh.CarriageRequest是代理,而这是一个包装好的原始实例.
This code is executed inside proxied object, so 'shipment' is always null, because 'sh.CarriageRequest == this' is always false. Because sh.CarriageRequest is a proxy, and this is a wrapped original instance.
推荐答案
好吧,NHibernate保证同一会话中已加载对象的引用相等.而且,如果使用延迟加载,它将使用代理包装实际对象,并且代理上的每个方法调用都将转发到包装的对象.因此,在此对象内,"this"与从会话加载的同一对象之间的每个引用比较都将失败(因为它将是一个不同的代理对象).
Okay, NHibernate guarantees reference equality for loaded objects within the same session. And if using lazy-loading, it wraps real object with a proxy and every method invocation on a proxy is forwarded to the wrapped object. So, inside this object every reference comparison between 'this' and the same object, loaded from session, will fail (because it will be a different, proxy, object).
因此,解决此问题的唯一方法是使用Equals方法或通过主键进行比较.
So, the only way to resolve this issue is to use Equals method or compare by primary keys.
这篇关于NHibernate,代理和平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!