NHibernate Futures有时返回代理,实体其他

kda*_*awg 2 c# nhibernate nhibernate-futures

我有一个数据库提取,使用多个未来查询处理完整的对象图.它看起来像这样(类名已被更改以保护无辜者):

Foo foo;
var fooFuture = Session.QueryOver<Foo>()
                       .Where(f => f.Id == id)
                       .Future();

// load up the Blah collection for the Foo
Session.QueryOver<Foo>()
       .Fetch(f => f.Blahs).Eager
       .Where(f => f.Id == id)
       .Future();

// do a separate query for the BlahOptions -- this is needed
// because if we did a Join and Join off of Foo, we'd get duplicate Blah
// results and that's not good
Session.QueryOver<Blah>()
       .Fetch(b => b.Options).Eager
       .Where(b => b.Foo.Id == id)
       .Future();

// load up the Attributes for the Foo
Session.QueryOver<Foo>()
       .Fetch(f => f.Attributes).Eager
       .Where(f => f.Id == id)
       .Future();

foo = fooFuture.SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)

注意:我可以在NHibernate LINQ中实现它,但行为保持不变.

古怪: foo有时会是类型FooNamespace.Foo(正确的,具体的类型),有时是它的类型Castle.Proxies.FooProxy.

我是否获得真实类型或代理类型似乎取决于NHibernate之前是否已在会话中使用过.当在其他NHibernate查询之后发生此查询时,它返回一个FooProxy.如果是第一次使用会话,则返回a Foo.

为什么会这样?我怎样才能防止它发生? 我有目的地获取整个对象图,Foo以确保没有代理.图表本身不包含任何代理,它只是根Foo参考.返回类型取决于NHibernate以前做过的事实似乎是关键(而且非常奇怪).

一对结束笔记:

  • NHibernateUtil.IsInitialized喂食a时返回true FooProxy,所以我不能保证它不是代理
  • 我是代理不利的,因为图表将被序列化以用于缓存目的和反序列化时使用时会出现问题 FooProxy

非常感谢任何见解!

san*_*rnc 9

通常会发生这种情况的原因是因为在此点之前会话中的Foo被加载到其他地方并且您正在获取在该先前查询上创建的代理.

我在以下方面取得了一些成功

var fooProxy = foo as INHibernateProxy;
if(fooProxy != null) {
   var context= Session.GetSessionImplementation().PersistenceContext;
   foo = context.Unproxy(fooProxy);
}
Run Code Online (Sandbox Code Playgroud)

但是,在大多数情况下,序列化过程似乎将Proxy转换为正确的类型.

  • 小点,但如果添加`using NHibernate.Proxy`,你可以用`foo.IsProxy()`调用替换null check. (3认同)