我正在学习 Fluent NHibernate(以及一般意义上的 NHibernate)。我正在使用带有一些覆盖的自动映射,但我认为这对问题并不重要(当然,如果我在这里错了,我会很乐意更新问题)。
给定一个 ISession
(以及更多假设的变量),我可以通过 ID 返回实体:
using (var session = SessionFactory.OpenSession())
{
var user = session.Get<User>(userId);
}
我有限的理解是 NHibernate 围绕 User
映射实体创建了一个代理,但是当我测试它时 (based on this):
Assert.That(user is INHibernateProxy, "Not a proxy.");
看来我的实例不是代理。
是否存在不使用代理的情况?我希望找到“缺失的部分”并祈祷这不是周五下午的脑力衰竭。
最佳答案
有些问题永远不会太老;) 在现实生活中,您通常通过访问反向关系的“父”或通过 Load() 加载对象来获取代理。但是如果这个对象之前已经被加载到缓存中,你会得到第一次访问的类型。所以 Load/Get 可能都返回代理或真实实例。
// if object has been loaded, load will return real instance
using (var session = CreateSession())
{
postByGet = session.Get<Post>(post1Id);
postByLoad = session.Load<Post>(post1Id);
Assert.IsFalse(postByGet is INHibernateProxy);
Assert.IsFalse(postByLoad is INHibernateProxy);
Assert.IsTrue(object.ReferenceEquals(postByGet, postByLoad));
}
// if proxy has been loaded, get will return filled proxy
using (var session = CreateSession())
{
postByLoad = session.Load<Post>(post1Id);
postByGet = session.Get<Post>(post1Id);
Assert.IsTrue(postByGet is INHibernateProxy);
Assert.IsTrue(postByLoad is INHibernateProxy);
Assert.IsTrue(object.ReferenceEquals(postByGet, postByLoad));
}
关于c# - 是否存在 NHibernate 不返回代理对象的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9843310/